单向链表的反序

链表的反序是链表的基本操作之一,简洁易读的反序操作实现也是体现一个人对链表的掌握程度。下面是我的一个链表实现方法,使用的是我的通用测试框架。

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

typedef struct node {
    struct node *next;
    int val;
}Node;


Node *reverse(Node *list)
{
    Node *pcur = NULL, *pnxt = NULL;

    if (NULL == list) {
        return NULL;
    }

    pcur = list->next;
    list->next = NULL;

    while (pcur) {
        pnxt = pcur->next;
        pcur->next = list;

        list = pcur;
        pcur = pnxt;
    }

    return list;
}

void printlist(Node *list)
{
    while (list) {
        printf("%d ", list->val);
        list = list->next;
    }
}

int main(int argc, char *argv[])
{
    int i;
    unsigned int len;
    Node *vector = NULL, *list = NULL;

    /* get the array lenth from input */
    scanf("%u", &len);

    vector = (Node *)malloc(len * sizeof(Node));
    if (NULL == vector) {
        return 1;
    }
    /* get the array value from input  */
    for (i=0; i<len; i++) {
        scanf("%d", &vector[i].val);
        if (i == len-1) {
            vector[i].next = NULL;
        } else {
            vector[i].next = &vector[i+1];
        }
    }

    list = reverse(vector);
    printlist(list);

    free(vector);
    return 0;
}

测试输入 5个节点的链表,各节点value值依次是 2 9 3 1 7

测试结果:

-bash-4.1$ ./link_reverse
5 2 9 3 1 7
7 1 3 9 2


发布了27 篇原创文章 · 获赞 2 · 访问量 4626

猜你喜欢

转载自blog.csdn.net/xqjcool/article/details/48339241