求C语言单链表倒序遍历程序~
发布网友
发布时间:2022-08-16 00:58
我来回答
共1个回答
热心网友
时间:2023-09-25 10:47
额。。写完了才发现好像题目意思理解错了,是倒序遍历啊,不过我已经把整个链表倒过来了,直接遍历即可,遍历完了可以再倒回去。。。= =要不你就按原本的顺序遍历,每次都插入到最前面,这样就新建一个链表和原本顺序相反,就可以了~
========================================================
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int value;
struct _node *next;
} node;
node * make_node(int value) {
node *new_node = (node *) malloc(sizeof(node));
new_node->value = value;
new_node->next = 0;
return new_node;
}
node * add_after(node *pos, int value) {
node *new_node = make_node(value);
pos->next = new_node;
return new_node;
}
void print_node_list(node *head) {
while (head) {
printf("%d ", head->value);
head = head->next;
}
printf("\n");
}
void free_node_list(node *head) {
node *temp;
while (head) {
temp = head;
head = head->next;
free(temp);
}
}
node * reverse(node *head) {
node *f = 0, *s = 0;
while (head) {
f = s;
s = head;
head = head->next;
s->next = f;
}
return s;
}
int main() {
int i = 0;
node *head = make_node(i), *last = head;
while (i < 10) {
last = add_after(last, ++i);
}
print_node_list(head);
head = reverse(head);
print_node_list(head);
free_node_list(head);
return 0;
}