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

发布评论
评论(7)
只有影子陪我不离不弃2022-09-09 10:43:22
C语言以前学过,现在忘光了,但是前几天刚好看到链表这块
我感觉是在链表里再加个struct Node_ *prev,用于指向上一个结点的地址
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
用递归就好了
来源:http://stackoverflow.com/questions/27047351/print-singly-linked-list-in-reverse-order