单链表c语言实现
作者:互联网
#include <stdio.h> #include <stdlib.h> typedef int ElemType; typedef struct Lnode{ ElemType data; Lnode *next; }Lnode,*LinkNode; int InitLinkList(LinkNode &L){ L = (LinkNode)malloc(sizeof(Lnode)); L -> next = NULL; printf("init success\n"); return 0; } int ListEmpty(LinkNode L){ if (L->next){ printf("Link is not null\n"); return 0; } printf("Link is null\n"); return 0; } int DestoryList (LinkNode &L){ LinkNode p; while(L){ p = L; L = L->next; free(p); } return 0; } int clearList(LinkNode &L){ LinkNode p,q; p = L->next; while(p){ q=p->next; free(p); p=q; } L->next = NULL; return 0; } int ListLength(LinkNode L){ LinkNode p; int i = 0; p = L->next; while(p){ i++; p = p->next; } printf("%d\n",i); return 0; } int GetElem(LinkNode L, int i){ int j =0; ElemType e; LinkNode p; p = L->next; while(p&&i>j){ p = L->next; j++; } e = p->data; printf("%d\n",e); return 0; } int GetElem_Data(LinkNode L, ElemType e){ LinkNode p; ElemType data; p = L->next; while(p){ data = p->data; if (data == e){ printf("find in link data is %d\n",e); return 0; } p = p ->next; } printf("elem not in link\n"); return 0; } int InsertLinkNode(LinkNode &L, int i, ElemType e){ LinkNode p,q; int j = 0; p = L; while(p&&j<i-1){ p = p->next; j++; } if(!p||j>i-1){ printf("链表溢出"); return 0; } q = (LinkNode)malloc(sizeof(Lnode)); q->data = e; q->next = p->next; p->next = q; return 0; } int ForData(LinkNode L){ LinkNode p; p = L; while(p->next){ p = p->next; printf("%d\n",p->data); } return 0; } int DeleteLinkNode(LinkNode &L, int i){ LinkNode p,q; int j = 0; p = L; while(p->next&&j<i-1){ p = p->next; j++; } if(!(p->next)||j>i-1){ printf("链表溢出"); return 0; } q = p->next; p ->next = q->next; return 0; } // //int InsertLinkNodeHead(LinkNode &L,ElemType e){ // pass //} // // //int InsertLinkNodeTail(LinkNode &L,ElemType e){ // pass //} int main(){ LinkNode L; InitLinkList(L); ListEmpty(L); for (int i=0;i<=10;i++){ InsertLinkNode(L,i+1,i); } InsertLinkNode(L,8,22); DeleteLinkNode(L,1); DeleteLinkNode(L,10); ForData(L); GetElem_Data(L,0); return 0; }
头插法尾插法未完成下周更新完。
标签:单链,return,语言,实现,data,next,int,printf,LinkNode 来源: https://www.cnblogs.com/Pynu/p/16180068.html