題目:
給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例:
給定 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
反思:
循環的代碼有點看不懂。。。但感覺主要考點就是遞歸,也不看了。。。