码迷,mamicode.com
首页 > 编程语言 > 详细

【C/C++】反转链表

时间:2014-06-26 12:10:06      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   ext   color   

/*
 * 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++】反转链表

标签:style   class   blog   code   ext   color   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!