leetcode 【 Reorder List 】python 实现
2015-01-09 23:19
543 查看
题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given
代码: oj 测试通过 248 ms
思路:
这道题的路子分三块:
1. 遍历单链表 求链表长度
2. 锁定后半个链表,反转后半个链表的每个元素
3. 切断前后半个链表的链接处 然后合并两个链表
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.
代码: oj 测试通过 248 ms
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return nothing def reorderList(self, head): if head is None or head.next is None or head.next.next is None: return head dummyhead = ListNode(0) dummyhead.next = head # get the length of the linked list p = head list_length = 0 while p is not None: list_length += 1 p = p.next #reverse the second half linked list fast = dummyhead for i in range((list_length+1)/2): fast = fast.next pre = fast curr = pre.next for i in range( (list_length)/2 - 1 ): tmp = curr.next curr.next = tmp.next tmp.next = pre.next pre.next = tmp #merge h2 = pre.next fast.next = None # cut the connection between 1st half linked list and 2nd half linked list while head is not None and h2 is not None: tmp = head.next head.next = h2 tmp2 = h2.next head.next.next = tmp h2 = tmp2 head = tmp return dummyhead.next
思路:
这道题的路子分三块:
1. 遍历单链表 求链表长度
2. 锁定后半个链表,反转后半个链表的每个元素
3. 切断前后半个链表的链接处 然后合并两个链表
相关文章推荐
- 【LEETCODE】143- Reorder List [Python]
- 【LeetCode with Python】 Reorder List
- leetcode reorder-list(java实现)
- [leetcode]Reorder List @ Python
- [Leetcode][python]Reorder List
- 【leetcode】Reorder List (python)
- LeetCode:Reorder List C++与Java实现
- 【leetcode】Reorder List (python)
- [LeetCode]题解(python):143-Reorder List
- LeetCode题解:Reorder List
- [LeetCode]Reorder List
- Reorder List [LeetCode]
- LeetCode Reorder List
- Reorder List @LeetCode
- LeetCode | Reorder List
- [LeetCode] Reorder List
- [leetcode]Reorder List
- Leetcode: Reorder List
- [LeetCode]Reorder List
- Leetcode: Reorder List