首页 > 其他 > 详细

【leetcode】143. Reorder List

时间:2019-03-19 17:49:47      阅读:125      评论:0      收藏:0      [点我收藏+]

题目如下:

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You may not modify the values in the list‘s nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

解题思路:我的方法是用一个list保存链表后半部分的节点,接下来从头开始遍历链表,把list中的第一个节点插入到原链表的第一个节点后,第二个插入到原链表的第二个节点后面,直到list全部节点都插入到原链表为止。

代码如下:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: None Do not return anything, modify head in-place instead.
        """
        if head == None:
            return
        mid,tail = head,head
        while tail != None:
            tail = tail.next
            if tail == None:
                break
            tail = tail.next
            if tail == None:
                break
            mid = mid.next
        l = []
        second_half = mid.next
        mid.next = None
        while second_half != None:
            l.insert(0,second_half)
            second_half = second_half.next

        current = head
        while len(l) > 0:
            node = l.pop(0)
            node.next = current.next
            current.next = node
            current = current.next.next

 

【leetcode】143. Reorder List

原文:https://www.cnblogs.com/seyjs/p/10559919.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!