题目:
给定一个单链表,成对交换相邻的两个节点,并返回链表头。
例如:
代码:
# 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 = new_head = ListNode(0)
while (head!=None and head.next!=None):
head_next = head.next
head_next_next = head.next.next
new_head.next = head_next
head_next.next = head
new_head = head_next.next
head = head_next_next
if head!=None:
new_head.next = head
else:
new_head.next = None
return pre.next