CPP单向链表学习心得

    科技2022-07-10  106

    #pragma once #include <iostream> using namespace std; typedef struct LinkNode { void* data; LinkNode* next; int size; }Linkn; typedef struct Linklist { LinkNode* head; int size; }LinkList,*PDLst; typedef void PRELINKNODE(void*); PDLst Iinit(); void insertvalue(PDLst pl, int pos,void* factor); void removebypos(PDLst pl, int pos); int getlength(PDLst pl); int findfactor(PDLst pl, void* data); void* returnfhead(PDLst pl); void printlinklist(LinkList* list, PRELINKNODE print); #include "linklist.h" #include <iostream> using namespace std; PDLst Iinit() { PDLst pl = (PDLst)malloc(sizeof(LinkList)); pl->head = (LinkNode*)malloc(sizeof(LinkNode)); pl->head->data = NULL; pl->head->next = NULL; pl->head->size = 0; return pl; } void insertvalue(PDLst pl, int pos, void* factor) { if (pl == NULL) { return; } if (pos > pl->size || pos < 0) { pos = pl->size; } LinkNode* pcurrent = pl->head; for (int i = 0; i < pos; i++) { pcurrent = pcurrent->next; } LinkNode* Newnode = (LinkNode*)malloc(sizeof(LinkNode)); Newnode->data = factor; Newnode->next = pcurrent->next; pcurrent->next = Newnode; pl->size++; } void removebypos(PDLst pl, int pos) { if (pl == NULL) { return; } if (pos>pl->head->size) { cout << "oversize" << endl; return; } LinkNode* pcurrent; pcurrent = pl->head->next; for (int i = 0; i < pl->head->size-1; i++) { pcurrent = pcurrent->next; } pcurrent->next = pcurrent->next->next; free(pcurrent->next); pl->size--; } int getlength(PDLst pl) { return pl->size; }; int findfactor(PDLst pl, void* data) { if (pl==NULL||data==NULL) { return NULL; } LinkNode* pcurrent = pl->head; for (int i = 0; i < pl->size; i++) { if (pcurrent->data == data) { return i; } pcurrent = pcurrent->next; } } void* returnfhead(PDLst pl) { if (pl == NULL) { cout << "not exists" << endl; return NULL; } return pl->head; } void myprint(void* data) { int* data2 = (int*)data; cout << *data2 << endl; } void printlinklist(LinkList* list,PRELINKNODE print) { if (list == NULL) { return; } LinkNode* pcurrent = (LinkNode*)malloc(sizeof(LinkNode)); pcurrent = list->head->next; cout << list->size << endl; while (pcurrent!=NULL) { print(pcurrent->data); pcurrent = pcurrent->next; } } int main() { Linklist* newlist = Iinit(); int a = 1; int a2 = 2; int a3 = 3; int a4 = 4; insertvalue(newlist, 1, &a); insertvalue(newlist, 2, &a2); insertvalue(newlist, 3, &a3); insertvalue(newlist, 4, &a4); printlinklist(newlist,myprint); system("pause"); return 0; }
    Processed: 0.011, SQL: 8