链表_leetcode143

# 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: void Do not return anything, modify head in-place instead.
"""

if not head or not head.next or not head.next.next:
return head



start = head
pre ,tail = self.findTailNode(head)


nextStart = start.next
pre.next = None

start.next = tail
tail.next = self.reorderList(nextStart)

return start


def findTailNode(self,head):

pre = head
tail = pre.next

while tail.next:

pre = tail
tail = tail.next

return pre ,tail





def creatList(self, l):
dummyHead = ListNode(0)

pre = dummyHead

for i in l:
pre.next = ListNode(i)
pre = pre.next

return dummyHead.next

def printList(self, head):
cur = head

while cur:
print cur.val
cur = cur.next

# 思路:
#
# 在中间平均截开两段,若为奇数,则第一段多一个
#
# 将第二段reverse
#
# 然后两段再交错地link起来

class Solution2(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if head is None or head.next is None or head.next.next is None:
head = head

else:
slow = fast = head
while fast.next and fast.next.next:
slow = fast.next
fast = fast.next.next


head2 = slow.next
slow.next = None

dummy = ListNode(0)
dummy.next = head2

p = head2.next
head2.next = None

while p:

# nextP = p.next
# p.next = dummy.next
# dummy.next = p
# p = nextP
tmp = p
p = p.next
tmp.next = dummy.next
dummy.next = tmp

head2 = dummy.next

p1 = head
p2 = head2

while p2:
t1 = p1.next
p1.next = p2

t2= p2.next
p2.next = t1

p1 = t1
p2 = t2


class Solution3(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if head is None or head.next is None or head.next.next is None:
head = head
else:

slow = fast = head # two parts
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next

head2 = slow.next
slow.next = None

dummy = ListNode(0) # reverse 2nd part
dummy.next = head2
p = head2.next
head2.next = None
while p:
tmp = p
p = p.next
tmp.next = dummy.next
dummy.next = tmp
head2 = dummy.next

p1 = head # rejoin 2 parts together
p2 = head2
while p2:
t1 = p1.next
p1.next = p2
t2 = p2.next
p2.next = t1
p1 = t1
p2 = t2










l1 = [1,2,3,4,5,6]

s = Solution()

head = s.creatList(l1)

s.printList(head)

head = s.reorderList(head)

s.printList(head)

posted @ 2019-03-19 10:56  AceKo  阅读(175)  评论(0编辑  收藏  举报