143.重排列表
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
思路
今天做了几道链表的题目,总结一下。
当遇到需要多次访问链表某个节点的时候,可以把它放进一个vector里面去,做到可以使用下标进行访问.
vector<Linknode* > res;
要寻找一个链表的中间节点,可以使用快慢指针进行求解,快慢指针在链表的作用很常见,比如找倒数第n个结点,带环链表的入口等等。
要记得想起可以使用快慢指针
code
/**
* 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 == nullptr ) return;
ListNode * node = head;
vector<ListNode*> res;
while(node!=nullptr)
{
res.emplace_back(node);
node = node->next;
}
int i = 0;
int j = res.size()-1;
while(i<j)
{
res[i]->next = res[j];
i++;
if(i== j) break;
res[j]->next = res[i];
j--;
}
res[i]->next = nullptr;
}
};
链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list