题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
个人思路:
递归。
官方答案推荐:
递归或正常的循环
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:return None
if not head.next:return head
newHead = head.next
nextNode = newHead.next
newHead.next = head
head.next = self.swapPairs(nextNode)
return newHead
反思:
循环的代码有点看不懂。。。但感觉主要考点就是递归,也不看了。。。