leetcode328:Odd Even Linked List

题目描述

将链表奇数序号的节点按序排到偶数序号节点前面
input: 1->4->5->8->7->null
output: 1->5->7->4->8->null


自己的丑陋代码

# easy
'''
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
'''
class Solution(object):
    L=None
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None:         
            return head
        slow=curr=currn=head
        count=1
        while curr and curr.next:
            precurr=curr
            curr=curr.next
            count+=1
            if count%2==1:
                currn=curr.next
                curr.next=slow.next
                slow.next=curr
                precurr.next=currn
                slow=slow.next
                curr=currn
                count+=1   
                # unitTest(head)              
        return head

# test code
    def unitTest(self,head):
        print("************test***************")
        curr=head
        print(curr.val)
        while curr.next:
            curr=curr.next
            print( '->',curr.val,end='' )

    def testConstruction(self):
        curr=self.L
        print(self.L,self.L.val)
        while curr.next:
            curr=curr.next
            print(curr,curr.val)

    def construction(self):
        self.L=ListNode(1)
        second=ListNode(2)
        # print(L,L.val,L.next)
        self.L.next=second
        # print(second,second.val,second.next)
        second=ListNode(3)
        self.L.next.next=second
        second.next=ListNode(4)
        second.next.next=ListNode(5)



ans=Solution()
ans.construction()
ans.testConstruction()
ans.oddEvenList(ans.L)   
  • 自己的代码写得不够优美机智,但是construction、testConstruction、unitTest等函数都可以在链表题中进行复用和本地的调试检查

大佬的代码

def oddEvenList(self, head):
    dummy1 = odd = ListNode(0)
    dummy2 = even = ListNode(0)
    while head:
        odd.next = head
        even.next = head.next
        odd = odd.next
        even = even.next
        head = head.next.next if even else None
    odd.next = dummy2.next
    return dummy1.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值