LeetCode题目记录
第24题:两两交换链表中的节点
1.题目链接
[https://leetcode-cn.com/problems/swap-nodes-in-pairs/]
2.题目内容
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
3.解题思路
本题需对链表所作的处理是对相邻的节点两两分组交换它们的位置。因此需要设置其迭代步长为2。交换节点的基本操作是改变连接节点的指针指向,由于需要考虑两个相邻节点的完整信息,所以将进行移动的单个窗格大小设置为四个节点,交换中间两个节点的位置。
4.代码实现
# 自己解法
#(甲)
# 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:
dummy = ListNode(-1)
dummy.next = head
temp = dummy
while temp.next and temp.next.next:
temp.next.next.next, temp.next.next, temp.next, temp=temp.next,temp.next.next.next,temp.next.next,temp.next
return dummy.next
#(乙)
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return head
cur = ListNode(0)
cur.next = head
first =cur
while cur.next and cur.next.next:
n1 = cur.next #赋值
n2 = n1.next #赋值
nxt = n2.next #赋值
n1.next = nxt #n1->n2.next表示指针方向
n2.next = n1 #n2->n1->n2.next表示指针方向
cur.next = n2 #cur->n2->n1->n2.next表示指针方向
cur = n1 #窗格向右移两个数字
return first.next