C语言实现一个单向链表,并写程序把单向链表进行逆序?

发布于 09-02 10:43 字数 1752 浏览 25 评论 0

图片描述

上图是题目需要实现的效果。
纯小白才开始学C语言,求指导,只输出了0到9,不知如何逆序输出。
中间重复的代码部分应该是要优化一下的,但暂时还不知到该怎么写。

#import <Foundation/Foundation.h>

typedef struct Node_ {
    int value;
    struct Node_ * next;
} Node;

Node *createNode(int value, Node *next) {
    Node* node = malloc(sizeof(Node));
    node->value = value;
    node->next = next;
    return node;
}

void printList(Node *firstNode) {
    for (Node *node=firstNode; node!=NULL; node=node->next) {
        printf("%d\n", node->value);
    }
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Node *current = createNode(0, NULL);
        Node *first = current;
        
        current->next = createNode(1, NULL);
        current = current->next;
        
        current->next = createNode(2, NULL);
        current = current->next;
        
        current->next = createNode(3, NULL);
        current = current->next;
        
        current->next = createNode(4, NULL);
        current = current->next;
        
        current->next = createNode(5, NULL);
        current = current->next;
        
        current->next = createNode(6, NULL);
        current = current->next;
        
        current->next = createNode(7, NULL);
        current = current->next;
        
        current->next = createNode(8, NULL);
        current = current->next;
        
        current->next = createNode(9, NULL);
        current = current->next;

        printList(first);
        char *str = "reversed:";
        printf("%s\n", str);
    }
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

棒棒糖2022-09-09 10:43:22

用递归就好了

void printReversedList(Node *firstNode){
    if(firstNode == NULL) return;
    printReversedList(firstNode->next);
    printf("%d\n", firstNode->value);
}

来源:http://stackoverflow.com/questions/27047351/print-singly-linked-list-in-reverse-order

捂风挽笑2022-09-09 10:43:22

遍历链表,从第一个节点开始,依次把节点push到栈中。遍历完成后,依次从栈中pop出来,同时打印即可。

@aluo1的答案用了递归,本质上也是用了栈,只不过是更底层的函数调用栈。

终难愈2022-09-09 10:43:22

已经有人回答了你的正面问题。
所以我就不重复了,但我想说:为什么不设计成双向的链表呢?如果可以的话应该尽量是双向的。

作妖2022-09-09 10:43:22

定义一个temp指针,一个一个往前指= =

静若繁花2022-09-09 10:43:22

链表反转图解

不知道这样你明白了没有。。。

飘逸的'云2022-09-09 10:43:22

是不是也可以用一个数组来存储,数组逆序输出。大家觉得不好,请喷

C语言以前学过,现在忘光了,但是前几天刚好看到链表这块

我感觉是在链表里再加个struct Node_ *prev,用于指向上一个结点的地址

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文