c Language Manually Implements Reverse of Reversed Linked List
Published: 2019-05-15

This topic requires the realization of a function that reverses a given single linked list.
Function interface definition:

List Reverse( List L );

where the List structure is defined as follows:

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

L is the list for a given order, and the function Reverse returns the reversed list.
Sample referee test procedure:

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

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

input sample:

5
1 3 4 5 2

Output Sample:

1
2 5 4 3 1

train of thought:
Just turn the pointer upside down. The tail pointer changes to the head pointer.

code:

List Reverse( List L )
{
    if(L == NULL)return NULL;
    List l1,l2;
    l1 = l2 = NULL;
    while(L!=NULL)
    {
        l1 = L->Next;//记录当前点的下一个结点的地址
        L->Next = l2;//当前点的NEXT指向前一个点
        l2 = L;//l2记录当前点的地址,方便下一个点用。
        L = l1;//L移向下一个要处理的点
    }
    return l2;
}