C语言实现链表重排:思路与代码示例
下面是使用C语言编写重排链表的基本思路:
- 首先,定义一个结构体来表示链表节点:
typedef struct Node {
int value;
struct Node* next;
} Node;
- 创建一个函数,用于创建链表。该函数接受一个整数数组和数组长度作为参数,并返回链表的头指针。函数的基本思路如下:
- 遍历整数数组,为每个数组元素创建一个链表节点。
- 将节点按照数组元素的顺序连接起来,形成一个链表。
以下是一个示例函数:
Node* createLinkedList(int arr[], int size) {
Node* head = NULL;
Node* current = NULL;
for (int i = 0; i < size; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->value = arr[i];
newNode->next = NULL;
if (head == NULL) {
head = newNode;
current = head;
} else {
current->next = newNode;
current = current->next;
}
}
return head;
}
- 编写一个函数来重排链表。该函数接受链表的头指针作为参数,并修改链表使得原链表的第一个节点指向最后一个节点,第二个节点指向倒数第二个节点,以此类推。函数的基本思路如下:
- 使用快慢指针技巧,找到链表的中间节点。
- 将链表的后半部分进行反转。
- 从头节点开始,依次交替连接前半部分链表节点和反转后的后半部分链表节点。
以下是一个示例函数:
void reorderLinkedList(Node* head) {
if (head == NULL || head->next == NULL) {
return;
}
// 找到链表的中间节点
Node* slow = head;
Node* fast = head;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
// 反转后半部分链表
Node* prev = NULL;
Node* current = slow->next;
while (current != NULL) {
Node* nextNode = current->next;
current->next = prev;
prev = current;
current = nextNode;
}
slow->next = NULL;
// 重排链表
Node* first = head;
Node* second = prev;
while (second != NULL) {
Node* nextNode1 = first->next;
Node* nextNode2 = second->next;
first->next = second;
second->next = nextNode1;
first = nextNode1;
second = nextNode2;
}
}
- 最后,在主函数中进行测试。创建一个链表,然后调用重排链表函数,并打印重排后的链表。
void printLinkedList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
Node* head = createLinkedList(arr, size);
printf("原链表:");
printLinkedList(head);
reorderLinkedList(head);
printf("重排后的链表:");
printLinkedList(head);
return 0;
}
这样,您就可以使用C语言实现链表的重排。请注意,这只是一个简单的示例,您可以根据自己的需求进行修改和扩展。编写代码时请记得在程序末尾释放动态分配的内存。祝您编程顺利!
原文地址: https://www.cveoy.top/t/topic/YLq 著作权归作者所有。请勿转载和采集!