Reverse Linked List

4-4 Reverse Linked List   (20分)

Write a nonrecursive procedure to reverse a singly linked list in O(N)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 oldlist=L->Next;
    List newlist;
    newlist=(struct Node*)malloc(sizeof(struct Node));
    newlist->Next=NULL;
    while(oldlist){
        struct Node* temp=oldlist->Next;
        oldlist->Next=newlist->Next;
        newlist->Next=oldlist;
        oldlist=temp;
    }
    //翻转原链表
    struct Node* tempnew=newlist->Next;
    struct Node* tempold=L;
    while(tempnew){
        tempold->Next=tempnew;
        tempold=tempold->Next;
        tempnew=tempnew->Next;
    }
    tempold->Next=NULL;
    return newlist;

}


  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值