标签: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;
}
标签:style class blog code ext color
原文地址:http://blog.csdn.net/xiewenbo/article/details/34803469