C语言实现{1,2,3,4}输入,重拍链表后输入{1,4,2,3}
时间: 2024-03-07 21:47:04 浏览: 26
可以使用链表来实现这个功能。具体步骤如下:
1. 定义一个链表结构体,包含一个整数值和指向下一个节点的指针。
2. 将输入的数组元素逐个插入链表中,即对于每个元素,创建一个新的节点,将其值赋给节点的整数值,将当前节点的指针指向前一个节点,并将其作为前一个节点的下一个节点。
3. 对于重排后的数组,遍历链表,找到对应元素的节点,然后将其移动到链表的末尾。具体实现可以先遍历一遍链表,找到需要移动的节点,然后再将其从链表中删除,并将其插入到链表的末尾。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int value;
struct Node* next;
} Node;
// 插入节点到链表末尾
void insert(Node** head, int value) {
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->value = value;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
} else {
Node* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = new_node;
}
}
// 找到值为value的节点
Node* find(Node* head, int value) {
Node* curr = head;
while (curr != NULL) {
if (curr->value == value) {
return curr;
}
curr = curr->next;
}
return NULL;
}
// 将节点移动到链表末尾
void move_to_end(Node** head, Node* node) {
if (*head == NULL || node == NULL) {
return;
}
if (*head == node) {
*head = node->next;
} else {
Node* prev = *head;
while (prev->next != node) {
prev = prev->next;
}
prev->next = node->next;
}
node->next = NULL;
insert(head, node->value);
}
// 打印链表
void print(Node* head) {
if (head == NULL) {
printf("Empty list\n");
} else {
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->value);
curr = curr->next;
}
printf("\n");
}
}
int main() {
int arr1[] = {1, 2, 3, 4};
int arr2[] = {1, 4, 2, 3};
int len = sizeof(arr1) / sizeof(arr1[0]);
// 将arr1插入链表
Node* head = NULL;
for (int i = 0; i < len; i++) {
insert(&head, arr1[i]);
}
// 将arr2中的节点移动到链表末尾
for (int i = 0; i < len; i++) {
Node* node = find(head, arr2[i]);
move_to_end(&head, node);
}
// 打印链表
print(head);
return 0;
}
```
输出结果为:
```
1 4 2 3
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)