6-4 Reverse Linked List (20 point(s))
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 pre=NULL;
List cur=L->Next;
while(cur){
List next = cur->Next;
cur->Next = pre; // 反转
pre = cur;
cur = next;
}
L->Next = pre;
return L;
}
本文介绍了一种在O(N)时间内使用常数额外空间非递归地反转单链表的方法。通过逐步交换节点指针,实现链表的反转,并确保反转后的链表有一个虚拟头节点。
844

被折叠的 条评论
为什么被折叠?



