给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
分析
- 区分 头部情况 中间情况 尾部情况
- 区分 偶数 奇数
- 判断是否为空链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# 空链表
if head is None:
return head
# 头部
pre = head
if pre.next is None:
# 判断是否只有头节点
return head
cur = pre.next
pre.next = cur.next
cur.next = pre
head = cur
# 中间
while cur.next.next is not None:
if cur.next.next.next is None:
# 判断是否是落单节点
return head
# 中间的 pre 指向当前要交换的两节点的前一个节点
pre = cur.next
# cur 指向要交换的两节点中第二个节点
cur = cur.next.next.next
pre.next.next = cur.next
cur.next = pre.next
pre.next = cur
return head