用python语言解答LeetCode的24题
碎碎念(不用看!下一节开始才是重点~~~)
念个啥呀,看了题目一脸懵逼的。。。。是不是要用到某种算法,类似递归?然后操作指针?然后脑袋一片空白了。。。
方法一:迭代
解题思路:先添加一个空头,再进行交换,以下图解为交换过程:
方法一的代码:
# 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, b = c.next, c.next.next
c.next, a.next = b, b.next
b.next = a
c = c.next.next
return thead.next
方法一的运行结果:
方法二:递归
Reference
1.方法一的思路来源
https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/bi-jiao-zhi-jie-gao-xiao-de-zuo-fa-han-tu-jie-by-w/