给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
画图!!!
1. 先定义一个头节点之前的节点
2. 判断的时候要注意需要两个条件都不为空
3. 更换指针
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(next=head)
cur = dummy_head
while cur.next and cur.next.next:
tmp = cur.next
tmp1 = cur.next.next.next
cur.next = tmp.next
tmp.next.next = tmp
tmp.next = tmp1
cur = cur.next.next
return dummy_head.next