c语言 反转链表 代码
时间: 2023-12-24 22:23:04 浏览: 101
反转链表是指将链表中的节点顺序颠倒过来。以下是一个C语言的反转链表代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int elem;
struct Node *next;
} node;
node *initNode() {
node *end = NULL;
node *p = (node *)malloc(sizeof(node));
p->next = NULL;
p->elem = 1;
end = p;
for (int i = 2; i <= 3; i++) {
node *newnode = (node *)malloc(sizeof(node));
newnode->next = NULL;
newnode->elem = i;
end->next = newnode;
end = newnode;
}
return p;
}
void show(node *p) {
node *temp = p;
while (temp) {
printf("%d ", temp->elem);
temp = temp->next;
}
printf("\n");
}
node *recursion(node *p) {
if (p == NULL || p->next == NULL) {
return p;
} else {
node *newnode = recursion(p->next);
p->next->next = p;
p->next = NULL;
return newnode;
}
}
int main(void) {
node *p = initNode();
show(p);
p = recursion(p);
show(p);
return 0;
}
```
阅读全文