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
用网上的链表反转是过不了的,因为这个还自带一个虚头。
注意print两次输出都是相同的值,说明L被反转以后并没有被消掉。
解法:
- 按网上的方法反转L->Next以后的内容,注意输入的带有一个虚头
- 反转链表时注意,反转两个结点的时候,记录下第三个结点的位置。
- 再把反转后的链表接到L后面,类似于L->Next=p;p是L后面的内容反转以后的第一个结点。