#include <stdio.h> #include <stdlib.h> #define OK 1#define ERR 0#define MAXSIZE 100typedef int elemtype;// define typedef struct NODE{ELEMTYPE data;struct Node *next;} node,*linkedlist;//Initialize LinkedList linkedlistinit () {Node *l; L = (node *) malloc (sizeof (node)), if (l==null) {printf ("Failed to request memory space."); L->next=null;return L; }//establishment of single-linked list 1, head insertion method to establish a single-linked list LinkedList linkedlistcreatehead () {Node *head; Head = (node *) malloc (sizeof (node));//Application head node space head->next=null; Elemtype x;//x is the data in the data field of the linked list while (scanf ("%d", &x)!=eof) {Node *p; p= (node *) malloc (sizeof (node)); p->data=x; p->next=head->next; Head->next=p;} return Head;} The establishment of single-linked list 2, the end of the insertion method to establish a single-linked list LinkedList linkedlistcreatetail () {//Application header node *head; Head = (node*) malloc (sizeof (Node)); The head->next=null;//definition Tail always points to the terminal node, and at the beginning points to the head node node *tail; Tail=head; Elemtype X;while (scanf ("%d", &x)!=eof) {Node *p = (node *) malloc (sizeof (node));//Apply for new node p->data=x; tail->next=p; Tail=p;} Tail->next=null;return Head;} The insertion of a single-linked list, inserting an element of x in the list I position LinkedList Linkedlistinsert (LiNkedlist l,int I,elemtype x) {Node *pre;pre = L;int temp=0;for (temp=1;temp<i;temp++) pre=pre->next; Node *p = (node *) malloc (sizeof (node)); P->data = x; P->next=pre->next;pre->next=p;return L;} Delete the single-linked list, delete the element with the value x in the list LinkedList Linkedlistdel (LinkedList l,elemtype x) {node *pre,*p;//p is the lookup node pre for the predecessor node p=l->next; while (p->data!=x) {pre=p;p=p->next;} Pre->next=p->next;free (P); return L;} Show single-linked list data void Linkedlistshow (LinkedList L) {linkedlist temp;int i=0;for (i=1,temp = l->next; temp! = NULL; i++,temp = tem P->next) printf ("(%d)->%d", i,temp->data); printf ("\ n");} int main () {///Keyboard Input EOF method: Press CTRL + Z on a new linelinkedlist l;//-tail interpolation method to build table printf ("Please enter data for single linked list: \ n"); L=linkedlistcreatetail ();p rintf ("The list is: \ n"); Linkedlistshow (L); int i; Elemtype x;printf ("Please enter the location and value of the inserted data, separated by a space: \ n"); scanf ("%d%d", &i,&x); Linkedlistinsert (l,i,x);p rintf ("The list is: \ n"); Linkedlistshow (L);p rintf ("Enter the value of the element to be deleted:"); scanf ("%d", &x); Linkedlistdel (L,X); printf ("The list is: \ n"); Linkedlistshow (L); return 0;}
The definition, initialization and operation of a single-linked list of linear tables