#include<stdio.h>#include<stdlib.h>structnode{intdata;structnode*next;};typedefstructnodeNode;intmain(intargc,char*argv[]){intnum;num=atoi(argv[1]);Node*first,*cur,*pre;for(inti=0;i<num;i++){cur=(Node*)malloc(sizeof(Node));cur->data=i+1;printf("Data for Node%d: %d\n",i+1,cur->data);if(i==0)first=cur;elsepre->next=cur;cur->next=NULL;pre=cur;}cur=first;while(cur!=NULL){printf("address=%p, ",cur);printf("data=%d ",cur->data);printf("next=%p\n",cur->next);cur=cur->next;}// free pointer
cur=first;Node*tmp;while(cur!=NULL){tmp=cur;cur=cur->next;free(tmp);return0;}
Result:
1
2
3
4
5
6
7
8
9
$ ./Linklist 4
Data for Node1: 1
Data for Node2: 2
Data for Node3: 3
Data for Node4: 4
address=0x7f8748c05840, data=1 next=0x7f8748c05850
address=0x7f8748c05850, data=2 next=0x7f8748c05860
address=0x7f8748c05860, data=3 next=0x7f8748c05870
address=0x7f8748c05870, data=4 next=0x0
Node*delete(Node*first,Node*node){Node*p=first;if(!p){printf("Nothing to delete\n");returnfirst;}if(first==node)first=first->next;else{while(p->next!=node)p=p->next;p->next=node->next;}free(node);returnfirst;}