建设网站教程2016seo推广薪资
143. 重排链表https://leetcode.cn/problems/reorder-list/
目录
解法一:公式化哈希解法
解法二:寻找链表中点 + 链表逆序 + 合并链表
给定一个单链表
L
的头节点head
,单链表L
表示为:L0 → L1 → … → Ln - 1 → Ln请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4] 输出:[1,4,2,3]示例 2:
输入:head = [1,2,3,4,5] 输出:[1,5,2,4,3]提示:
- 链表的长度范围为
[1, 5 * 104]
1 <= node.val <= 1000
解法一:公式化哈希解法
使用哈希表存放链表结点,再按题目要求逻辑进行拼接。
map<int, ListNode*> dict;
dict.insert(pair(count++, cur));
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:void reorderList(ListNode* head) {// 使用map来存放每个链表结点map<int, ListNode*> dict;int count = 0; // count进行计数ListNode* cur = head;while(cur){dict.insert(pair(count++, cur));cur = cur->next;}// 进行后续拼接操作ListNode* newhead = new ListNode(-1);ListNode* pre = newhead;int left = 0, right = count-1;count = 0;while(left <= right){if(count++ % 2 == 0)cur = dict[left++];elsecur = dict[right--];cur->next = nullptr;pre->next = cur;pre = cur;}head = newhead->next;}
};
此题的随机访问特性也可以使用vector进行存储。
vector<ListNode*> dict;
dict.push_back(cur);
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:void reorderList(ListNode* head) {// 使用map来存放每个链表结点vector<ListNode*> dict;int count = 0; // count进行计数ListNode* cur = head;while(cur){// dict.insert(pair(count++, cur));dict.push_back(cur);count++;cur = cur->next;}// 进行后续拼接操作ListNode* newhead = new ListNode(-1);ListNode* pre = newhead;int left = 0, right = count-1;count = 0;while(left <= right){if(count++ % 2 == 0)cur = dict[left++];elsecur = dict[right--];cur->next = nullptr;pre->next = cur;pre = cur;}head = newhead->next;}
};
解法二:寻找链表中点 + 链表逆序 + 合并链表
注意到目标链表即为将原链表的左半端和反转后的右半端合并后的结果。
咱这规律也没发现……看了思路自己写吧。
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:void reorderList(ListNode* head) {if(!head && head->next != nullptr)return;// 1、利用快慢指针找到链表的中间结点ListNode* slow = head, *fast = head;while(fast->next != nullptr && fast->next->next != nullptr){slow = slow->next;fast = fast->next->next;}// 2、反转后半部分链表ListNode* newhead = new ListNode(-1);newhead->next = nullptr;while(slow){fast = slow->next;slow->next = newhead->next;newhead->next = slow;slow = fast;}// 3、合并这俩个链表ListNode* l1 = head;ListNode* l2 = newhead->next;while(l1 && l2){// 用fast和slow分别记录l1和l2后面指针fast = l1->next;slow = l2->next;l1->next = l2;l1 = fast;l2->next = l1;l2 = slow;}}
};