该题目是算法导论10.2-7的习题,拿出来做下,题目要求O(n)的非递归过程,且除了链表本身占用的空间外,该过程仅使用固定量的存储空间。

代码如下:

/********************************************************************************

**

** Filename: ReverseList.cpp

**

** Description: reverse a list by two methods: recursive and nonrecursive

**

** Version: 1.0

** Created: 2012年02月09日 12时18分59秒

*********************************************************************************/

#include <iostream>

using namespace std;

typedef struct node{

node(int d=int(), node *n=NULL) :

data(d) ,

next(n)

{

}

int data;

node *next;

}node;

node *head;

void print(const char *s)

{

cout << s << endl;

node *temp = head;

while (temp!=NULL) {

cout << temp->data << " ";

temp = temp->next;

}

cout << endl;

}

void reverseListNonRecursive()

{

print("before reverse list nonrecursive:");

node *temp = head;

node *next = temp->next;

node *prev = NULL;

while (temp!=NULL) {

next = temp->next;

temp->next = prev;

prev = temp;

temp = next;

}

head = prev;

print("after reverse list nonrecursive:");

}

void reverseListRecursive(node* n)

{

node* nextNode = n->next;

if (nextNode==NULL) {

head = n;

return;

}

reverseListRecursive(nextNode);

nextNode->next = n;

}

void reverseListRecursive()

{

print("before reverse list recursive:");

node* temp = head;

reverseListRecursive(head);

temp->next = NULL;

print("after reverse list recursive:");

}

int main()

{

node n5(5);

node n4(4,&n5);

node n3(3,&n4);

node n2(2,&n3);

node n1(1,&n2);

head = &n1;

reverseListNonRecursive();

reverseListRecursive();

return 0;

}


输出:

zhy@desktop:~/doublemint/factory$ ./a.out

before reverse list nonrecursive:

1 2 3 4 5

after reverse list nonrecursive:

5 4 3 2 1

before reverse list recursive:

5 4 3 2 1

after reverse list recursive:

1 2 3 4 5

个人感觉非递归和递归过程都有一点要注意的地方:

1. 非递归要记录previous,current,next三个结点,这样代码编写会很方便。如果只用两个指针应该也行,但我没想出来怎么做。

2. 递归。。。真心难懂,想了很久,发现代码写起来很短。。。