重排链表 给定一个单链表 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.
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reorder-list
整体思路:
栈 (1)全体节点按顺序入栈 (2)移动tmp指针作为前节点和弹出栈顶元素作为后节点(类似前后指针),作为新链的节点 (3)判断tmp指针是否等于栈顶元素 (4)新链尾节点置空 代码:
class Solution { public: void reorderList(ListNode* head) { if (head == nullptr) return; stack<ListNode*> node_stk; ListNode* tmp = head->next; ListNode* p1 = head; ListNode* p2 = head; //入栈 while (p1) { node_stk.push(p1); p1 = p1->next; } //如果节点小于等于2,链不改变 if (node_stk.size() <= 2) return; while(tmp!=node_stk.top()){//节点树为偶数的停止条件 if (p2 == nullptr) break;//防止p2为空指针操作 p2->next = node_stk.top(); p2 = p2->next; p2->next = tmp; p2 = p2->next; if (tmp != nullptr && tmp->next != nullptr) tmp = tmp->next;//防止tmp为空指针操作 if (tmp == node_stk.top()) {//节点树为奇数的停止条件 p2->next = nullptr; return; } node_stk.pop(); } p2->next = node_stk.top(); p2->next->next = nullptr; //清空堆栈 while (!node_stk.empty()) { node_stk.pop(); } return; } };复杂度分析
时间复杂度:O(n) 空间复杂度:O(n)
开销较大,更多算法查看官方题解