#include <stdio.h>
#include <stdlib.h>
typedef struct NODE
{
int data;//node Data
struct node *next;//pointer to the next node of the node
}listnode,*list;//list point to this node
Initializing a single-linked list
List initlist (void)
{
List Mylist=malloc (sizeof (ListNode));//malloc allocates space, creates a node as the head node, and points mylist to it
if (mylist!=null)
{
mylist->next=null;
}//determines whether the space is allocated successfully, and if successful, points the node of the head node to an empty
return mylist;
}
Returns a pointer to the head node
List NewNode (int n)
{
List New=malloc (sizeof (ListNode));
if (new!=null)
{
new->data=n;
new->next=null;
}
return new;
}
Create a new node
void Insertlist (List new,list mylist)
{
List p=mylist;
if (new==null)
Return
while (P->next!=null)
{
p=p->next;
}
new->next=p->next;
p->next=new;
}
Insert a new node after the list
There are several steps to inserting a node in a linked list. 1. Be sure to insert it there. 2. The pointer to be inserted points to the next pointer (new->next=p->next;) of the inserted node, and the next pointer of the inserted node points to the node to be inserted (p->next=new;)
void Showlist (List mylist)
{
List q=mylist->next;
while (Q!=null)
{
printf ("%d", q->data);
q=q->next;
}
printf ("\ n");
}//Display linked list
void revert (List mylist)
{
List p=mylist->next;//p the first meta-node
List tmp;
tmp=p->next; (You must first assign a value to TMP, and if you execute mylist->next=null First, a segment error will occur )
mylist->next=null;
while (Tmp!=null)
{
tmp=p->next;
p->next=mylist->next;
mylist->next=p;
p=tmp;
}
}//the reverse function, starting with the first node, inserting each node into the head node until the last node, so that the last node is placed on the first node.
int main ()
{int n,j;
List mylist=initlist ();//define the head pointer and make it point to the head node
printf ("Please enter the number of linked list j\n");
scanf ("%d", &j);
while (j>0)
{
scanf ("%d", &n);
List New=newnode (n);
Insertlist (new,mylist);
--j;
}
Showlist (MyList);
Revert (MyList);
Showlist (MyList);
GetChar ();
return 0;
}
Use a single linked list to reverse the data