题目描述(中等难度)
解题思路
把链表的值存储到列表当中,然后两两再进行翻转
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)