将链表的前半部分和后半部分交换C语言
时间: 2024-05-16 18:11:54 浏览: 9
以下是将链表的前半部分和后半部分交换的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
Node* create(int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
void insert(Node** head, int data) {
Node* new_node = create(data);
if (*head == NULL) {
*head = new_node;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new_node;
}
}
void print(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
void swap(Node** head) {
Node* slow = *head;
Node* fast = *head;
Node* prev_slow = NULL;
while (fast != NULL && fast->next != NULL) {
prev_slow = slow;
slow = slow->next;
fast = fast->next->next;
}
if (fast != NULL) {
slow = slow->next;
}
Node* temp = *head;
*head = slow;
prev_slow->next = NULL;
Node* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = temp;
}
int main() {
Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
printf("Original list: ");
print(head);
swap(&head);
printf("Swapped list: ");
print(head);
return 0;
}
```
在函数`swap`中,我们用两个指针`slow`和`fast`来找到链表的中间节点,然后将链表分成前半部分和后半部分。我们将前半部分的尾节点与后半部分的头节点连接起来,然后返回新的头节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)