Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
有一种代码叫做别人的代码
而且最开始还看错了 以为是反转链表MDZZ
先看我丑陋的代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
p=ListNode(0)
p.next=head
l1=ListNode(0)
l1=head
l2=ListNode(0)
l2=l1.next
l1.next=l2.next
l2.next=l1
head=l2
p.next=l2
while(1):
l1=l1.next
if l1==None:
break
l2=l1.next
if l2==None:
break
p=p.next
p=p.next
l1.next=l2.next
l2.next=l1
p.next=l2
return head
再看看人家的
话说 等号运算符是从右向左进行运算的呢
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre,pre.next=self,head
while pre.next!=None and pre.next.next!=None:
a=pre.next
b=a.next
pre.next,b.next,a.next=b,a,b.next
pre=a
return self.next