Created
September 11, 2012 00:35
-
-
Save kelvin-fly/3695097 to your computer and use it in GitHub Desktop.
the basic of link's use
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<stdio.h> | |
| #include<malloc.h> | |
| typedef int DataType; | |
| typedef struct Node | |
| { | |
| DataType data; | |
| struct Node *next; | |
| }LNode, *PNode, *LinkList; | |
| int main(int argc,char * argv[]) | |
| { | |
| int i; | |
| int data[7]={1,2,3,4,5,6,7}; | |
| DataType item; | |
| LinkList h=NULL; | |
| InitList(&h); | |
| for(i=0;i<7;i++) | |
| { | |
| if(!ListInsert(h,i+1,data[i])) | |
| { | |
| printf("Insert error!!!\n"); | |
| return 0; | |
| } | |
| } | |
| printf("\n\ndelete NOde data\n"); | |
| TraverseList(h); | |
| if(!ListDelete(h,5,&item)) | |
| { | |
| printf("Delete error!!!\n"); | |
| return 0; | |
| } | |
| printf("\n\ndelete data\n"); | |
| TraverseList(h); | |
| DestroyList(h); | |
| return 0; | |
| } | |
| int InitList(LinkList *h) | |
| { | |
| *h=(LinkList)malloc(sizeof(LNode)); //create head node | |
| if(!h) | |
| { | |
| printf("Initialise head point error!!!\n"); | |
| return 0; | |
| } | |
| (*h)->next = NULL; | |
| return 1; | |
| } | |
| int ListInsert(LinkList h,int pos,DataType x) | |
| {/*pos means the insert position,x means the data waitting to insert*/ | |
| PNode p=h,q; | |
| int i=0; | |
| while(p&&i<pos-1) | |
| { | |
| p=p->next; | |
| i++; | |
| } | |
| if(!p||i>pos-1) | |
| { | |
| printf("illegal inserting position!!!\n"); | |
| return 0; | |
| } | |
| q=(PNode)malloc(sizeof(LNode)); | |
| if(!q) | |
| { | |
| printf("canot creat new node\n"); | |
| return 0; | |
| } | |
| q->data=x; | |
| q->next=p->next; | |
| p->next=q; | |
| return 1; | |
| } | |
| void TraverseList(LinkList h) | |
| { | |
| PNode p=h->next; | |
| while(p) | |
| { | |
| printf("%d\t",p->data); | |
| p=p->next; | |
| } | |
| printf("\n"); | |
| } | |
| int ListDelete(LinkList h, int pos,DataType *item) | |
| { | |
| PNode p=h,q; | |
| int i=0; | |
| while(p->next && i<pos-1) //find | |
| { | |
| p=p->next; | |
| i++; | |
| } | |
| if(!p->next || i>pos-1) | |
| { | |
| printf("the deleting position is wrong"); | |
| return 0; | |
| } | |
| q=p->next; | |
| p->next=q->next; | |
| *item=q->data; | |
| free(q); | |
| return 1; | |
| } | |
| int DestroyList(LinkList h) | |
| { | |
| PNode p=h->next; | |
| while (h) | |
| { | |
| p=h; | |
| h=h->next; | |
| free(p); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment