两两交换链表中的节点
两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
Python
解一:
# 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
"""
p = ListNode(next = head)
if head != None and head.next != None:
head = head.next
while p.next != None and p.next.next != None:
temp = p.next.next
p.next.next = p.next.next.next
temp.next = p.next
p.next = temp
p = p.next.next
return head
解二:
# 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
"""
def swap(head):
if head == None or head.next == None:
return head
first = head
second = head.next
others = head.next.next
second.next = first
first.next = swap(others)
return second
return swap(head)
笔记
- 这道题解一思路较为简单,只要注意需要用到中间变量temp,保证不会有节点丢失即可,可以画图来辅助解题;
- 解二使用了递归,根据题意我们可以知道这个过程始终是first与second所指链点交换位置,而下一轮first和second也能在上一轮过程中得到,因此可以使用递归的做法,要注意返回值。
浙公网安备 33010602011771号