PTA 数据结构与算法题目集(中文)6-1 单链表逆转(20)

本题要求实现一个函数,将给定的单链表逆转。

函数接口定义:

List Reverse( List L );

其中List结构定义如下:

typedef struct Node *PtrToNode;
struct Node {
    ElementType Data; /* 存储结点数据 */
    PtrToNode   Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

L是给定单链表,函数Reverse要返回被逆转后的链表。

裁判测试程序样例:

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

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

List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表 */

List Reverse( List L );

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

/* 你的代码将被嵌在这里 */

输入样例:

5
1 3 4 5 2

输出样例:

1
2 5 4 3 1
C语言代码如下:
List Reverse(List L)     //题目所给的接口函数
{
    struct Node *pre=NULL;   //pre为指向空的指针
    struct Node *curr=L;     //curr为指向当前位置(即为L指向的位置)的指针
    while(curr) 
    {
        struct Node *next=curr->Next;  //next指向的为curr指向的节点的下一个节点
        curr->Next=pre;               //当前节点指向前一个节点
        pre=curr;                     //将前一个节点(pre)移动到下一个节点(curr)的位置
        curr=next;                    //将当前节点(curr)移动到下一个节点(next)的位置
    }
    return pre;   //返回pre指针(此时指向为原单链表的最后一个节点)
}

猜你喜欢

转载自blog.csdn.net/H1727548/article/details/129049270