Inverted linked list (c++ version) includes (create linked list print linked list inverted linked list)

Create a linked list: head insertion method
For personal understanding: the process of creating a linked list is to gradually apply for space and perform assignment operations at the same time. The linked list can be regarded as a cabinet for storing clothes in the bathroom (but not one by one, it can be divided into discrete parts), the upper grid is used to store data, and the lower grid is used for addresses, which are used to connect the next cabinet. Multiple cabinets are connected to form a linked list. To perform other operations Without further
ado, the code is as follows:
insert image description here
Apply for the head node space in the main function, and the operation is as follows:
insert image description here
Print the linked list:
traverse the output from the head node to find the stop of the traversal is the key
insert image description here
Invert the linked list: The
idea requires three pointers to perform the inversion operation
pq pn
initialization p = head ->next ; q =NULL; head->next=NULL; (reserving the head node)
traverse the linked list pn = p->next ; p->next=q; q=p; p=pn;
finally head->next=q;

insert image description here

Give 1 to q (q=p) , p=2(p=pr) and perform the
specific code in turn:

insert image description here

All code (if the humble author doesn't like it, don't spray it, if you have any ideas, please don't hesitate to let me know):

#include<iostream>
using namespace std;
struct List
{
    
    
	int data;
	struct List *next;
 } ;
  //创建链表
 void Create(List * head); 
 //打印链表
 void Prin(List *head); 
 //倒置 
 List *reverse(List *head); 
 int main()
 {
    
    
 	List *head=NULL;
 	head=new List;
 	Create(head);
	Prin(head); 
 	head=reverse(head);
 	Prin(head);
 	return 0;
 }
 
 //创建链表
 void Create(List * head)
 {
    
    
	for(int i=0;i<4;i++)
 	{
    
    
 		List *p=new List;
 		p->data=i;
 		p->next=NULL;
 		head->next=p;
 		head=p;
	 }
} 

 //打印链表
 void Prin(List *head)
 {
    
    
 	while(head->next!=NULL)
 	{
    
    
 		cout<<head->next->data<<" ";
 		head=head->next;
	 }
 	cout<<endl;
 }
 
  //倒置   返回头节点 
List *reverse(List *head){
    
    
	List *p,*q,*pr;
 	p=head->next;
    q=NULL;
    head->next=NULL;
 	while(p)
 	{
    
    
 		pr=p->next;
 		p->next=q;
 		q=p;
 		p=pr;
	 }
	 head->next=q;
  return head;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324148634&siteId=291194637