反转链表——临时变量的妙用

#include<iostream>
using namespace std;

struct Node{
public:
	int data;
	struct Node *next;
	Node(int data, Node *next): data(data), next(next){}
};

void print(Node *tmp){
	while(tmp != NULL){
		cout<<tmp->data<<endl;
		tmp = tmp->next;
	}	
}

Node *Initialize(){
	struct Node *head = new struct Node(0, NULL);
	Node *tmp(NULL), *last(head);
	for(int i=1; i<10; ++i){
		tmp = last;
		last = new Node(i, NULL);	
		tmp->next = last;
	}
	return head;	
}

Node *Reverse(Node *head){
	Node *tmp = head;
	Node *last, *second;
	while(tmp != NULL){
		second = tmp->next;
		if(tmp == head)
			tmp->next = NULL;
		else{
			tmp->next = last;
		}
		last = tmp;
		tmp = second;
	}
	head = last;
	return head;	
}

int main()
{
    Node *head = Initialize(); 
	head = Reverse(head);
	print(head);
	return 0;	
}

反转链表非常简单,循环链表把next拆开指向前一个就行了

在循环的过程中用了临时变量last来表示上一次反转到哪里了,同时用临时变量second表示下一次需要反转的

因为当前的next已经被拆断指向前面一个。

原文地址:https://www.cnblogs.com/lovelyxia/p/1945742.html