首页 > 编程语言 > 详细

【C/C++】反转链表

时间:2014-06-26 12:09:41      阅读:364      评论:0      收藏:0      [点我收藏+]
/*
 * reverseList.c
 *
 *  Created on: 2014年6月25日
 *      Author: wenbo
 */

#include <iostream>
using namespace std;
struct Node {
	Node* next;
	int data;
};
void trace(Node* node) {
	Node* tmp = node;
	while (tmp != NULL) {
		cout << tmp->data << " ";
		tmp = tmp->next;
	}
	cout<<endl;
}
Node* reverse(Node* node) {
	Node* first = node;
	Node* second = node->next;
	Node* tmp = second->next;
	Node* newHead;
	<span style="color:#ff0000;">first->next = NULL;//set head node as the last node</span>
	while (second != NULL) {
		second->next = first;
		first = second;
		second = tmp;
		if(tmp!=NULL){
			newHead = tmp;
			tmp = tmp->next;
		}
	}
	return newHead;
}
int main() {
	Node* node5 = new Node();
	node5->data = 5;
	node5->next = NULL;

	Node* node4 = new Node();
	node4->data = 4;
	node4->next = node5;

	Node* node3 = new Node();
	node3->data = 3;
	node3->next = node4;

	Node* node2 = new Node();
	node2->data = 2;
	node2->next = node3;

	Node* node1 = new Node();
	node1->data = 1;
	node1->next = node2;

	Node* root = new Node();
	root->data = 0;
	root->next = node1;

	cout<<"origin list:"<<endl;
	trace(root);
	Node* newRoot = reverse(root);
	cout<<"reversed list:"<<endl;
	trace(newRoot);
	return 0;
}

【C/C++】反转链表,布布扣,bubuko.com

【C/C++】反转链表

原文:http://blog.csdn.net/xiewenbo/article/details/34803469

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!