1. 程式人生 > >24. Swap Nodes in Pairs - Medium

24. Swap Nodes in Pairs - Medium

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:

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

 

每次交換兩個節點,用一個dummy node,放在head前,用以最後return head,需要兩個指標,起始時p1 = dummy, p2 = head

先記錄一下p2.next.next的位置 (nextnode),此位置也是下一次swap的起點。p1指向p2.next,p2.next指向p2,p2指向nextnode。然後p1向前一步移動到p2位置,p2向前移動到nextnode的位置,直到 p1.next == null或者 p2.next = null,迴圈結束

e.g.
0 -> 1 -> 2 -> 3 -> 4 -> null      0->2, 2->1, 1->3 => 2->1->3->4->null
p1                   n
  p2

0 -> 2 -> 1 -> 3 -> 4 -> null      1->4, 4->3, 3->null => 1->4->3->null
      p1        n
       p2

0 -> 2 -> 1 -> 4 -> 3 -> null      1->4, 4->3, 3->null => 1->4->3->null
           p1
            p2

time: O(n), space: O(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) {
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p1 = dummy, p2 = head; while(p1.next != null && p2.next != null) { ListNode nextnode = p2.next.next; p1.next = p2.next; p2.next.next = p2; p2.next = nextnode; p1 = p2; p2 = nextnode; } return dummy.next; } }