#include <stdio.h> #include <stdlib.h>struct linklist{int data;struct linklist *next;};/ * Initialize linked list */void init_list (linklist **head) {*head= (linklist *) malloc (sizeof (linklist));(*head)->next=null; }/* Add node */void add_node (linklist *head) {int x; linklist *p,*q;q=head;printf ("Input Add a data:"); scanf ("%d", &x); while (Q->next) q=q->next;p= (linklist *) malloc (sizeof (linklist));p->data=x; P->next=q->next;q->next=p;} /* Find the first node, return the node pointer */linklist *get_node (linklist *head,int i) {linklist *p=head;int j=0; while (p->next&&j<i) {p=p->next;j++;} if (j=i) return P;elsereturn NULL;} /* Find nodes by value, return node pointer */void get_value (linklist *head,int x) {int flag=0; Linklist *p=head;while (p->next) {p=p->next;if (p->data==x) {printf ("%d\n", p->data); flag=1;break;}} if (!flag) printf ("fail!\n");} /* Insert node before node I in the list */void insert_node (linklist *head,int i,int x) {linklist *p,*q;q= (linklist *) malloc (sizeof (linklist) );p =get_node (head,i-1), if (p) {q->next=p->next;p->next=q; Q->data=x;} elseprintf ("Node in not exist!\n", i);} /* Delete the I node */void delete_node (linklist *head,int i) {linklist *p,*q; P=get_node (head,i-1); Q=get_node (head,i); if (q!=null) {p->next=q->next;free (q);} else printf ("node in Not exist!\n");} /* Modify the list I node */void modify_node (linklist *head,int i,int x) {linklist *p;p=get_node (head,i), if (P!=null) p->data=x;} /* Show data for nodes in the list */void show (Linklist *head) {linklist *p;p=head->next;p=head;while (p->next) {p=p->next;printf ( "%2d", P->data);} printf ("\ n");} int main () {struct linklist *p; P=new linklist; int ch,i,x; Init_list (&P); Add_node (P); while (1) {printf ("******************************************************\n"); printf ("1.add 2.get node by index 3.get node by value 4.insert \ 5.delete 6.modify 7.show 0.quit\n"); printf ("******************************************************\n"); printf ("Please input your choice:"); scanf ("%d", &ch); Switch (CH) {case 1:add_node (p), break, Case 2: {printf ("Input a number:"); scanf ("%d", &i); printf ("%d\n", (linklist *) Get_node (p,i)->data); Case 3: {printf ("Input value of x:"); scanf ("%d", &x); Get_value (P,X); Break } Case 4: {printf ("Input values of I and x:"); scanf ("%d%d", &i,&x); Insert_node (p,i,x); Break }case 5: {printf ("Input value of I:"); scanf ("%d", &i); Delete_node (p,i); break;} Case 6: {printf ("Input values of I and x:"); scanf ("%d%d", &i,&x); Modify_node (P,I,X); Break }case 7:show (P); Break Case 0:exit (0); default:printf ("error! Please input again:\n "); Break }} return 0; }
Using C language to realize the operation of single-linked list