Linked list in situ reverse order

Linked list in situ reverse order

Topic information

Please write a function void inverse( LinkList )to realize the in-situ inversion of the singly linked list.
That is to use the original node to L =(a1, a2, …… , an)
transform the linear table: into:L =( an, …… , a2, a1)

Pre-code:

#include <iostream>
using namespace std;

typedef int ElemType;
typedef struct node
{
    
       ElemType    data;
    struct node * next;
} NODE;
typedef NODE * LinkList;

void output( LinkList );
void change( int, int, NODE * );
LinkList createList( ElemType );
void inverse( LinkList ); 

LinkList createList( ElemType finish )	//finish:数据结束标记 
{
    
    
    ElemType x;
    NODE *newNode; 
    LinkList first = new NODE;   // 建立头结点
    first->next = NULL;
    first->data = finish;
    cin >> x;	      			// 约定以finish结束连续输入
    while ( x != finish )
	{
    
    
        newNode = new NODE;      // 建立新结点
       	newNode->data = x;
       	newNode->next = first->next; // ①
      	first->next = newNode;       // ②
		cin >> x;
    }
    return first;
}

void output( LinkList head )
{
    
       cout << "List:";
	while ( head->next != NULL )
	{
    
       cout << head->next->data << ",";
		head = head->next;
	}
	cout << endl;
}

int main(int argc, char** argv) 
{
    
    
	LinkList head;

	head = createList( -1 );
	output( head );
	inverse( head );
	output( head );
	return 0;
}
Test input Expect output
Test case 1 10 20 30 40 -1 List:40,30,20,10,
List:10,20,30,40,
Test case 2 10 -1 List:10,
List:10,

answer

void inverse(LinkList head)
{
    
    
    LinkList p = head->next;
    head->next = NULL;
    while (p != NULL)
    {
    
    
        LinkList succ = p->next;
        p->next = head->next;
        head->next = p;
        p = succ;
    }
}

Guess you like

Origin blog.csdn.net/zhj12399/article/details/109223282