Description
- Swap Nodes in Pairs medium
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example
Given 1->2->3->4, you should return the list as 2->1->4->3.
题目大意
将一链表的奇偶数位上的值交换,要求不可改变链表结点值,只能改变其结点
解体思路
参考k个链表合并的思路,先将链表置于列表中,然后对列表中的奇偶数位上的值交换。如果列表长为偶数,则直接交换奇偶位值;如果列表长为奇数,直接交换的话最后一位操作会越界,所以可以先作判断如果是最后的奇数位,则直接加入结果列表中。
code
# 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:
l = []
while head:
l.append(head.val)
head = head.next
if len(l) == 1:
return l
res = []
for i in range(len(l)):
if len(l) % 2 == 0 :
if i % 2 == 0:
res.append(l[i+1])
res.append(l[i])
elif len(l) % 2 == 1:
if i == len(l) - 1:
res.append(l[i])
elif i % 2 == 0:
res.append(l[i+1])
res.append(l[i])
return res
参考较优解
解题思路
通过移动链表指针来实现。cur指向头结点,cur.next指向要交换的第一个数,cur.next.next指向要交换的第二个数,那么两数交换时,cur首先要指向要交换的第二个数,然后要交换的第一个数指向要交换的第二个数后面的数,要交换的第二个数指向要交换的第一个数,以此类推。
这里注意,先要使要交换的第一个数指向要交换的第二个数后面的数,否则,后面的链表断开,无法完成操作。
code
# 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
cur = dummy
while cur.next!= None and cur.next.next != None:
s1 = cur.next
s2 = cur.next.next
cur.next = s2
s1.next = s2.next
s2.next = s1
cur = s1
return dummy.next