- 题目描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
- 示例
给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
- 解决方案
定义指针first和second,分别指向要交换的两个节点,交换之后second在first的前面
为了方便操作,在头结点之前加上一个extr节点
另外有一个节点始终指向要交换的两个节点的前驱节点
- 代码
# 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
"""
#定义了一个前驱节点但是暂时没有指向头
extr = ListNode(0)
#如果链表为空,直接返回None
if head is None:
return None
# pre.next = head
#用first和second分别指向需要交换的两个节点
pre = extr
first = head
second = head.next
#如果第二个节点为空,直接返回第一个节点
#因为在接下来的while循环里,并没有针对这种情况作出处理
if second is None:
return head
#判断要当前要交换的第二个节点是否为空
while second:
#交换节点的值
pre.next = second
first.next = second.next
second.next = first
#pre节点前移,移到往后两个节点的前一个节点处
pre = first
#调整first和second指向下一次要交换的两个节点
first = first.next
#要注意判断此时的first是否已经是空
if first:
second = first.next
else:
second = None
return extr.next