2, insert (plug)
Suppose there are 2 consecutive nodes p in a single linked list. Q (where P is the direct precursor to Q), if we need to insert a new node s between P and Q, then we have to allocate space and assign a value for s, then we can store the address of S in the chain field of P, and the chain of S will store the address of Q. (P->LINK=S;S->LINK=Q), which completes the insert operation.
The following example is an example of applying an insert algorithm:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define N 10
typedef struct NODE
{
Char name[20];
struct node *link;
}stud;
Stud * creat (int n)/* Create a single linked list function * *
{
Stud *p,*h,*s;
int i;
if ((h= (Stud *) malloc (sizeof (stud))) ==null)
{
printf ("Cannot allocate memory space!");
Exit (0);
}
H->name[0]= ' ";
h->link=null;
P=h;
for (i=0;i<n;i++)
{
if ((s= (Stud *) malloc (sizeof (stud))) ==null)
{
printf ("Cannot allocate memory space!");
Exit (0);
}
p->link=s;
printf ("Please enter the name of person%d:", i+1);
scanf ("%s", s->name);
s->link=null;
P=s;
}
return (h);
}
Stud * Search (stud *h,char *x)/* Lookup function * *
{
Stud *p;
Char *y;
p=h->link;
while (P!=null)
{
y=p->name;
if (strcmp (y,x) ==0)
return (p);
else p=p->link;
}
if (p==null)
printf ("No find this data!");
}
void Insert (stud *p)/* Insert function, insert after pointer p * *
{
Char stuname[20];
Stud *s; /* Pointer S is to save the new node address * *
if ((s= (Stud *) malloc (sizeof (stud))) ==null)
{
printf ("Cannot allocate memory space!");
Exit (0);
}
printf ("Please enter the name of the person you want to insert:");
scanf ("%s", stuname);
strcpy (S->name,stuname); /* Copies the array elements pointed to by the pointer stuname to the data field of the new node * *
s->link=p->link; * * To point the link field of the new node to the subsequent node of the original P node.
p->link=s; The link field of the/*p node points to the new node * *.
}
Main ()
{
int number;
Char fullname[20]; /* Save the name of the person you have entered for search.
Stud *head,*searchpoint;
Number=n;
Head=creat (number); /* Create a new linked list and return to the table head pointer * *
printf ("Please enter the name of the person you are looking for:");
scanf ("%s", FullName);
Searchpoint=search (Head,fullname); /* Find and return the found node pointer.
Insert (Searchpoint); /* Call Insert Function * *
}