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

#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/archive/2011/01/26/1945742.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值