1. 程式人生 > >[LeetCode] 24. Swap Nodes in Pairs

[LeetCode] 24. Swap Nodes in Pairs

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

題目

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  1. Your algorithm should use only constant extra space.
  2. You may not modify the values in the list’s nodes, only nodes itself may be changed.

題目大意

將連結串列中 相鄰的結點 進行交換。
要求space n(1)。

思路

因為需要改變頭結點所以使用了一個輔助頭結點。使得程式碼更一致,無需 特別 處理 頭結點。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution { public ListNode swapPairs(ListNode head) { ListNode nhead = new ListNode(0); nhead.next = head; ListNode fp = nhead; while(fp.next!=null && fp.next.next!= null){ ListNode sp = fp.next; ListNode tp = fp.next.next; sp.
next = tp.next; tp.next = sp; fp.next = tp; fp = fp.next.next; } return nhead.next; } }

看了 答案的寫法 基本一致,現在主要的突破點是 提升 coding 速度。