leetcode---reorder-list---链表中点、逆转
2017-10-18 19:49
281 查看
Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→…
You must do this in-place without altering the nodes’ values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→…
You must do this in-place without altering the nodes’ values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *findMid(ListNode *head) { ListNode *fast = head; ListNode *slow = head; while(fast->next && fast->next->next) { fast = fast->next->next; slow = slow->next; } return slow; } ListNode *reverse(ListNode *head) { if(!head || !head->next) return head; ListNode *nextH = head->next; ListNode *newH = reverse(nextH); nextH->next = head; head->next = NULL; return newH; } ListNode *merge(ListNode *l, ListNode *r) { ListNode *p = l; ListNode *q = r; while(q) { ListNode *pNext = p->next; ListNode *qNext = q->next; p->next = q; q->next = pNext; p = pNext; q = qNext; } return l; } void reorderList(ListNode *head) { if(!head) return; ListNode *m = findMid(head); ListNode *r = m->next; m->next = NULL; ListNode *right = reverse(r); head = merge(head, right); } };
相关文章推荐
- (LeetCode)Reverse Linked List --- 逆转链表
- reorder-list——链表、快慢指针、逆转链表、链表合并
- LeetCode刷题笔记(链表):reorder-list
- C实现 LeetCode->Reorder List (双指针大法)(单链表是否有环)
- 【LeetCode】Middle of Linked List 查找链表中点 - Easy
- leetcode---linked-list-cycle---链表中点
- Reverse linked list(逆转从n到m处的单链表)--leetcode
- Leetcode: reorder-list
- 【leetcode 链表 】Insertion Sort List
- leetcode 61 --Rotate List 链表 循环/断开 翻转
- [LeetCode]Sort List 链表排序 + Merge Two Sorted List 合并两个有序链表
- Linked List Cycle leetcode II java (寻找链表环的入口)
- [LeetCode] Delete Node in a Linked List 删除链表的节点
- leetcode 148. Sort List 链表归并排序
- leetcode_c++:链表:Reorder List(143)
- LeetCode 141. Linked List Cycle (链表循环)
- LeetCode(Remove Duplicates from Sorted List) 两道删除排序链表中重复数字
- Leetcode解题-链表(2.2.6)RotateList
- leetCode-linkedListCycle判断链表是否有环
- LeetCode-Insertion Sort List-链表插入排序-链表操作