6-5 Reverse Linked List (15 分)

6-5 Reverse Linked List (15 分)
Write a nonrecursive procedure to reverse a singly linked list in O(N) time using constant extra space.

Format of functions:

List Reverse( List L );
where List is defined as the following:

typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node {
    ElementType Element;
    Position Next;
};

The function Reverse is supposed to return the reverse linked list of L, with a dummy header.

Sample program of judge:

#include <stdio.h>
#include <stdlib.h>

typedef int ElementType;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node {
    ElementType Element;
    Position Next;
};

List Read(); /* details omitted */
void Print( List L ); /* details omitted */
List Reverse( List L );

int main()
{
    List L1, L2;
    L1 = Read();
    L2 = Reverse(L1);
    Print(L1);
    Print(L2);
    return 0;
}

/* Your function will be put here */

Sample Input:

5
1 3 4 5 2

结尾无空行
Sample Output:

2 5 4 3 1
2 5 4 3 1

结尾无空行

代码解决办法如下:

List Reverse( List L )
{
	List rev;
	List cic;
    List save;
	cic = L->Next;
	while(cic != NULL){
		save = cic->Next;
		cic->Next = rev;
		rev = cic;
		cic = save;
	}
	//rev->Next = NULL;
	L->Next = rev;
	return L;
}

之所以要注释掉倒数第三行代码,是因为虽然cic不会取到NULL,但是save会取到原来L中的NULL,所以是已经有了NULL的。

欢迎交流。

上一篇:16、有n个正数,使得前面每个数依次后移m个位置,最后m个数变成最前面m个数


下一篇:【C语言程序设计第四版】例10-3, 10-4代码