leetcode 143. 重排链表 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

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值