leetcode 143. 重排链表 python

  • Post author:
  • Post category:python


题目描述:

题解:

1.通过slow fast指针找到链表中间位置。

2.对后半部分链表进行反转。

3.将前半部分链表和反转后的后半部分进行交叉。

尝试一(使用链表长度作为终止判断,未通过)链表节点为偶数正确,奇数结果不正确。

class Solution(object):
    def reorderList(self, head):
        head1 = head
        length = 0
        while head1:
            length = length + 1
            head1 = head1.next
        print(length)
        slow = head
        fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        print(slow)

        def reverse(head):
            pre = None
            cur = head
            nxt = head.next
            while nxt:
                cur.next = pre
                pre = cur
                cur = nxt
                nxt = cur.next
            cur.next = pre
            return cur

        cur = reverse(slow.next)
        print(cur)

        print(head)
        newhead = ListNode()
        nowlength = 0

        while True:
            newhead.next = head
            head = head.next
            newhead = newhead.next
            nowlength = nowlength + 1
            print(nowlength)
            print(newhead)
            if nowlength == length:
                return newhead.next

            newhead.next = cur
            cur = cur.next
            newhead = newhead.next
            nowlength = nowlength + 1
            print(nowlength)

            if nowlength == length:
                return newhead.next 

尝试二:

class Solution(object):
    def isPalindrome(self, head):
        if head==None or head.next==None:
            return True
        if head.next.next ==None:
            return head.val==head.next.val
        half1 = head
        slow = head
        fast = head
        while fast.next and fast.next.next:
            fast = fast.next.next
            slow = slow.next

        def reversed(head):
            if head == None:
                return head
            pre = None
            cur = head
            nxt = cur.next
            while nxt:
                cur.next = pre
                pre = cur
                cur = nxt
                nxt = nxt.next
            cur.next = pre
            return cur


        half2 = reversed(slow.next)
        print(slow)

        while half2.next:
            if half1.val != half2.val:
                return False
            half1 = half1.next
            half2 = half2.next
        return half1.val == half2.val



版权声明:本文为laurasam原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。