I used the header plug method.
# Include <stdio. h>
# Include <malloc. h>
# Define ture 1
# Define flase 0
# Define OK 1
# Define error 0
# Define Infeasible-1
# Define overflow-2
Typedef int status;
Typedef int elemtype;
Typedef struct lnode
{
Elemtype data;
Struct lnode * next;
} Lnode, * linklist;
// Create a linked list
Void buildlist_l (linklist & L, int N)
{
Linklist P;
L = (linklist) malloc (sizeof (lnode ));
L-> next = NULL;
Printf ("Enter the element value :");
For (INT I = 0; I <n; I ++)
{
P = (linklist) malloc (sizeof (lnode ));
Scanf_s ("% d", & P-> data); // input element value
P-> next = L-> next;
L-> next = P; // insert to the header
}
}
Status listinsert_l (linklist & L, int I, elemtype E)
{
// Insert element E before position I in the single-chain linear table l of the leading node of I
Linklist P;
Linklist S;
P = L;
Int J = 0;
While (P & J <I-1) // find I-1 nodes
{
P = p-> next;
++ J;
}
If (! P | j> I-1)
Return Error; // I is less than 1 or greater than the table length plus 1
S = (linklist) malloc (sizeof (lnode); // generate a new node
S-> DATA = E; // insert to L
S-> next = p-> next;
P-> next = s;
Return OK;
}
// Delete the linked list
Status listdelete_l (linklist & L, int I, elemtype & E)
{
// Delete the I-th element in the single-chain linear table l of the leading node and return its value by E.
Linklist P;
Linklist Q;
P = L;
Int J = 0;
While (p-> next & J <I-1)
{
P = p-> next;
++ J;
}
If (! (P-> next) | j> I-1)
Return Error; // the error message returned when the node is deleted is invalid.
// Delete and release the node
Q = p-> next;
P-> next = Q-> next;
E = Q-> data;
Free (Q );
Return OK;
}
Void printflist (linklist & L)
{
Linklist P;
P = L-> next;
If (P = NULL)
Printf_s ("This linked list is empty \ n ");
Else
{
While (P)
{
Printf_s ("% d", p-> data );
P = p-> next;
}
}
}
Void main ()
{
Linklist L;
Int A = 0; // A indicates the chain table length.
Printf_s ("Enter the number of elements in the linked list to be created :");
Scanf_s ("% d", & );
Buildlist_l (L, );
Printf_s ("output current linked list :");
Printflist (L );
Printf_s ("\ n ");
Int x = 0, y = 0; // X indicates the position of the element to be inserted, and y indicates the value of the element to be inserted.
Printf_s ("Enter the position of the element to be inserted and the value of the element :");
Scanf_s ("% d", & X, & Y );
Listinsert_l (L, x, y );
Printf_s ("output current linked list :");
Printflist (L );
Printf_s ("\ n ");
Int m = 0, n = 0; // M indicates the location of the element to be deleted, and N indicates the value of the element to be deleted.
Printf_s ("Enter the position and value of the element to be deleted :");
Scanf_s ("% d", & M, & N );
Listdelete_l (L, M, N );
Printf_s ("output current linked list :");
Printflist (L );
Printf_s ("\ n ");
}
Create, insert, delete, and output a linked list