C语言实现可变链表重排,并按{}逗号分隔输出
时间: 2023-07-11 09:30:25 浏览: 47
以下是在C语言中实现可变链表重排的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
int data;
struct node* next;
} node;
// 插入节点
void insert(node** head, int data) {
node* new_node = (node*) malloc(sizeof(node));
new_node->data = data;
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;
}
}
// 移动节点
void move_node(node** head, node* node_to_move) {
if (node_to_move == NULL || *head == NULL || node_to_move == *head) {
return;
}
node* curr = *head;
while (curr->next != NULL && curr->next != node_to_move) {
curr = curr->next;
}
if (curr->next == node_to_move) {
curr->next = node_to_move->next;
node_to_move->next = NULL;
curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = node_to_move;
}
}
// 重排链表
void reorder_list(node** head) {
if (*head == NULL || (*head)->next == NULL) {
return;
}
node* slow = *head;
node* fast = (*head)->next;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
node* head2 = slow->next;
slow->next = NULL;
node* prev = NULL;
node* curr = head2;
while (curr != NULL) {
node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head2 = prev;
node* curr1 = *head;
node* curr2 = head2;
while (curr1 != NULL && curr2 != NULL) {
node* next1 = curr1->next;
node* next2 = curr2->next;
curr1->next = curr2;
curr2->next = next1;
curr1 = next1;
curr2 = next2;
}
}
// 输出链表
void print(node* head) {
if (head == NULL) {
printf("NULL\n");
} else {
printf("%d", head->data);
node* curr = head->next;
while (curr != NULL) {
printf(", %d", curr->data);
curr = curr->next;
}
printf("\n");
}
}
int main() {
node* head = NULL;
// 输入链表
char input[100];
printf("请输入链表中的元素,以空格分隔,以回车键结束:\n");
fgets(input, 100, stdin);
char* token = strtok(input, " ");
while (token != NULL) {
insert(&head, atoi(token));
token = strtok(NULL, " ");
}
// 重排链表
reorder_list(&head);
// 输出链表
printf("重排后的链表为:\n");
print(head);
return 0;
}
```
输入示例:
```
1 2 3 4 5
```
输出示例:
```
重排后的链表为:
1, 5, 2, 4, 3
```