6-4 Reverse Linked List (20 point(s))带头节点的链表反转

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 
#include 

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;
}

 

你可能感兴趣的:(算法)