用c语言编写代码:已知有一个链表,任意输入一个值,实现链表的顺序插入及链表反序.
时间: 2023-07-11 18:40:41 浏览: 96
链表的定义如下:
```c
typedef struct node {
int data; // 存储节点的值
struct node *next; // 下一个节点
} Node, *LinkedList;
```
链表的顺序插入可以通过遍历链表,找到插入位置后,将节点插入到链表中。
```c
// 链表的顺序插入
void insert(LinkedList *list, int value) {
Node *new_node = (Node *) malloc(sizeof(Node));
new_node->data = value;
new_node->next = NULL;
if (*list == NULL) {
*list = new_node;
} else {
Node *p = *list;
while (p->next != NULL) {
p = p->next;
}
p->next = new_node;
}
}
```
链表的反序可以通过遍历链表,将每个节点插入到头部,实现链表的反序。
```c
// 链表的反序
void reverse(LinkedList *list) {
if (*list == NULL || (*list)->next == NULL) {
return;
}
Node *p = *list;
Node *q = (*list)->next;
(*list)->next = NULL;
while (q != NULL) {
Node *temp = q->next;
q->next = p;
p = q;
q = temp;
}
*list = p;
}
```
完整的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data; // 存储节点的值
struct node *next; // 下一个节点
} Node, *LinkedList;
// 链表的顺序插入
void insert(LinkedList *list, int value) {
Node *new_node = (Node *) malloc(sizeof(Node));
new_node->data = value;
new_node->next = NULL;
if (*list == NULL) {
*list = new_node;
} else {
Node *p = *list;
while (p->next != NULL) {
p = p->next;
}
p->next = new_node;
}
}
// 链表的反序
void reverse(LinkedList *list) {
if (*list == NULL || (*list)->next == NULL) {
return;
}
Node *p = *list;
Node *q = (*list)->next;
(*list)->next = NULL;
while (q != NULL) {
Node *temp = q->next;
q->next = p;
p = q;
q = temp;
}
*list = p;
}
// 遍历链表
void print_list(LinkedList list) {
while (list != NULL) {
printf("%d ", list->data);
list = list->next;
}
printf("\n");
}
int main() {
LinkedList list = NULL;
int value;
while (scanf("%d", &value) == 1) {
insert(&list, value);
}
printf("顺序插入:");
print_list(list);
reverse(&list);
printf("链表反序:");
print_list(list);
return 0;
}
```
阅读全文