题目描述
将链表奇数序号的节点按序排到偶数序号节点前面
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