阿里的面试题目:
# 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
pre = ListNode(0)
pre.next = head
first = head
second = head.next
p = pre
while first and second:
first.next = second.next
second.next = first
p.next = second
p = first
first = first.next
if first:
second = first.next
return pre.next
递归的做法,他们都是天才
# 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
new_head, head.next, new_head.next = head.next, self.swapPairs(head.next.next), head
return new_head