您的位置:首页 > 房产 > 家装 > LeetCode //C - 143. Reorder List

LeetCode //C - 143. Reorder List

2024/12/23 0:16:23 来源:https://blog.csdn.net/navicheung/article/details/139282447  浏览:    关键词:LeetCode //C - 143. Reorder List

143. Reorder List

You are given the head of a singly linked-list. The list can be represented as:

L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list’s nodes. Only nodes themselves may be changed.
 

Example 1:

在这里插入图片描述

Input: head = [1,2,3,4]
Output: [1,4,2,3]

Example 2:

在这里插入图片描述

Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]

Constraints:
  • The number of nodes in the list is in the range [ 1 , 5 ∗ 1 0 4 ] [1, 5 * 10^4] [1,5104].
  • 1 <= Node.val <= 1000

From: LeetCode
Link: 143. Reorder List


Solution:

Ideas:
  1. Find the middle of the linked list: We can use the fast and slow pointer technique to find the middle node.
  2. Reverse the second half of the linked list: Once we find the middle, we need to reverse the second half of the list.
  3. Merge the two halves: Finally, we merge the two halves by alternating nodes from the first half and the reversed second half.
Code:
/*** Definition for singly-linked list.* struct ListNode {*     int val;*     struct ListNode *next;* };*/
void reorderList(struct ListNode* head) {if (!head || !head->next) return;// Step 1: Find the middle of the linked liststruct ListNode *slow = head, *fast = head;while (fast->next && fast->next->next) {slow = slow->next;fast = fast->next->next;}// Step 2: Reverse the second half of the liststruct ListNode *prev = NULL, *curr = slow->next, *next = NULL;while (curr) {next = curr->next;curr->next = prev;prev = curr;curr = next;}slow->next = NULL; // Cut the list into two halves// Step 3: Merge the two halvesstruct ListNode *first = head, *second = prev;while (second) {struct ListNode *tmp1 = first->next, *tmp2 = second->next;first->next = second;second->next = tmp1;first = tmp1;second = tmp2;}
}// Helper function to create a new ListNode
struct ListNode* newNode(int val) {struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));node->val = val;node->next = NULL;return node;
}// Helper function to print the linked list
void printList(struct ListNode* head) {while (head) {printf("%d -> ", head->val);head = head->next;}printf("NULL\n");
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com