题目描述
解题思路
解法一:迭代法
原链表:
添加空头后的链表:
第一次交换:
①
②
③
python代码
# 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:
thead = ListNode(-1)
thead.next = head
c = thead
while c.next and c.next.next:
a = c.next
b = c.next.next
c.next = b
a.next = b.next
b.next = a
c = c.next.next
return thead.next
解法二
将链表的值存到列表中,再两两翻转
python代码
# 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 not head or not head.next:
return head
a = []
tem = ListNode(-1)
p = tem
# 把链表的值存储到列表当中
while head:
a.append(head.val)
head = head.next
b = len(a)//2
# 两两进行交换
for i in range(0,b*2,2):
a[i],a[i+1] = a[i+1],a[i]
# 再重新创建链表
for j in a:
p.next = ListNode(j)
p = p.next
return tem.next
s = Solution()
res = s.swapPairs(head)
print(res)