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; } }

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/10122632.html