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

查看:197
本文介绍了C语言实现一个单向链表,并写程序把单向链表进行逆序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

上图是题目需要实现的效果。
纯小白才开始学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;
}

解决方案

用递归就好了

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

这篇关于C语言实现一个单向链表,并写程序把单向链表进行逆序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆