[Leetcode]24: Swap Nodes in Pairs

Link : https://leetcode.com/problems/swap-nodes-in-pairs/

Problem :
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)

給一個Linklist,把相鄰的node進行交換
Note : 不能修改 Node上的Value

圖來自leetcode

Thoughts :
0. 準備一個prev,接上linklist,整個linklist變成 prev->1->2->3->4
1. 2指給1
2. 1指給3,整個linklist變成 prev->2->1->3->4
3. 開始更新指標,prev指標更新給1,head指標更新給3,開始下一輪更新

Solution :

Solution : (Recursive)

#time complexity, space complexity

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store