Inverted list of stack

Insert picture description here
Through the question, we know that this question requires knowledge of linked lists. First of all, friends who are not familiar with linked lists can first review the linked lists and understand the various basic operations of singly linked lists. To realize the inversion of the linked list, the first thing I think of is the stack, because the characteristic of the stack is first-in, first-out.

typedef struct lnode{
    
    
	int data;		//定义单链表 
	lnode *next;
}lnode,*list;

The typedef keyword means to alias the data type. The following list pointer is to make it more convenient to use later, and there is no need to define the pointer every time.

void lt(list &l){
    
    	//通过引用对头节点导出 
	int x;
	l=(list)malloc(sizeof(lnode));
	lnode *s,*r=l;
	cin>>x;
	while(x!=-1){
    
    			//输入数据,输入-1时退出循环 
		s=(list)malloc(sizeof(lnode));
		s->data=x;
		r->next=s;				
		r=s;
		cin>>x;
	}
	r->next=NULL;	//将尾节点的next值赋空值 
}

This is to construct a singly linked list through user input, using -1 as the termination condition, and don’t forget to assign a null value to the pointer field of the tail node at the end! (Don't forget to include the header file when using malloc to allocate space) The #include<malloc.h>
specific construction method is not very clear in text. If you don't understand it, you can go to Bilibili to look at the data structure of Wangdao Postgraduate. There is a detailed explanation. .
Insert picture description here

int main(){
    
    
	list l;
	lt(l);	//调用方法传入头结点 
	lnode *s;
	s=(list)malloc(sizeof(lnode));
	lnode *p;
	p=(list)malloc(sizeof(lnode));
	s->next=p;
	p->data=l->next->data;
	l=l->next;
	p->next=NULL;		//到这一步是将头结点与尾节点赋值链接 
	while(l->next!=NULL){
    
    
		lnode *r;
		r=(list)malloc(sizeof(lnode));
		r->next=p;
		r->data=l->next->data;		//利用了栈的先进后出的特点,限制数据只允许在头结点后面进行插入,构成新的链表 
		p=s->next=r;
		l=l->next;
	}
	while(s->next!=NULL){
    
    
		cout<<s->next->data<<" ";
		s=s->next;					//遍历新链表 
	}
	
}

The characteristics of the stack are used here to restrict the insertion of a singly linked list after the head node every time it is inserted, forming a new linked list, traversing the new linked list, and completing the inversion operation of the linked list.
Insert picture description here
This time the platform let me pass, hehe, great!

Guess you like

Origin blog.csdn.net/xszdbc/article/details/109324979
Recommended