code:
1 #include<iostream> 2 #include<stdlib.h> 3 using namespace std; 4 typedef int status; 5 typedef int elemType; 6 typedef struct lNode 7 { 8 elemType num; 9 struct lNode *next; 10 }lNode,*linkNode; 11 12 linkNode initListNode(); 13 void echNode(linkNode L); 14 linkNode insertNode(linkNode L); 15 void creatList(linkNode L,int n); 16 void echList(linkNode L); 17 linkNode delNode(linkNode L,int n); 18 linkNode searchNode(linkNode head,int n); 19 int main() 20 { 21 22 linkNode l,m; 23 l=initListNode(); 24 printf("After Initialization: "); 25 echNode(l); 26 printf(" Creat and echo List: "); 27 creatList(l,4); 28 echList(l); 29 printf(" Find 2nd elemet: "); 30 m=searchNode(l,2); 31 printf("Find result: "); 32 echNode(m); 33 printf(" Delt nodes and echo List "); 34 m=delNode(l,1); 35 m=delNode(m,1); 36 echList(m); 37 } 38 39 linkNode initListNode() 40 { 41 linkNode L; 42 L=(linkNode)malloc(sizeof(lNode)); 43 L->num=0; 44 L->next=NULL; 45 return L; 46 } 47 void creatList(linkNode L,int n) 48 { 49 int i; 50 for(i=0;i<n-1;i++) 51 { 52 L=insertNode(L); 53 L->num=i+1;//num value 54 } 55 56 } 57 58 void echNode(linkNode L) 59 { 60 printf("Node num is %d ",L->num); 61 } 62 linkNode insertNode(linkNode L) 63 { 64 linkNode tmpp; 65 tmpp=(linkNode)malloc(sizeof(lNode)); 66 //tmpp->num=9; 67 tmpp->next=NULL; 68 L->next=tmpp; 69 return tmpp; 70 } 71 72 void echList(linkNode L) 73 { 74 linkNode tmpp; 75 tmpp=L; 76 do 77 { 78 echNode(tmpp); 79 tmpp=tmpp->next; 80 } 81 while(tmpp); 82 } 83 84 linkNode searchNode(linkNode head,int n) 85 { 86 linkNode tmpp; 87 tmpp=head; 88 //printf(" Search %dnd element!! ",n); 89 while(--n) 90 { 91 if(tmpp->next) 92 { 93 tmpp=tmpp->next; 94 } 95 else 96 { 97 //cout<<"Over max quantity of Nodes of the List"; 98 exit(0) ; 99 } 100 } 101 //printf("The num is %d. ",tmpp->num); 102 return tmpp; 103 } 104 105 linkNode delNode(linkNode head,int n) 106 { 107 linkNode tmpp,nodep; 108 if(n>1) 109 { 110 tmpp=searchNode(head,n-1); 111 nodep=tmpp->next; 112 tmpp->next=tmpp->next->next; 113 free(nodep); 114 return head; 115 } 116 else if(n=1) 117 { 118 tmpp=head->next; 119 free(head); 120 return tmpp; 121 } 122 }
result:
After Initialization: Node num is 0 Creat and echo List: Node num is 0 Node num is 1 Node num is 2 Node num is 3 Find 2nd elemet: Find result: Node num is 1 Delt nodes and echo List Node num is 2 Node num is 3 请按任意键继续. . .