Given a linked list, swap every two adjacent nodes and return its head.node
Example:spa
Given , you should return the list as .1->2->3->42->1->4->3
Note:code
交換鏈表中的節點,題目不難,須要細心,有兩種解法。blog
1.遞歸,邏輯清晰。用臨時節點保存交換中的中間節點,以防鏈表斷裂,節點丟失。遞歸
class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode temp = head.next; head.next = swapPairs(head.next.next); temp.next = head; return temp; } }
2.直接循環作,須要一個假的頭節點來保存交換以後的頭節點,一樣須要臨時節點保存交換中的中間節點。it
class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode fakeHead = new ListNode(0), pre = fakeHead, temp = null; fakeHead.next = head; while (pre.next!=null && pre.next.next!=null) { temp = pre.next.next; pre.next.next = temp.next; temp.next = pre.next; pre.next = temp; pre = temp.next; } return fakeHead.next; } }
在LeetCode上循環比遞歸耗時減小1msio