Home LeetCode. 24. Swap Nodes in Pairs
Post
Cancel

LeetCode. 24. Swap Nodes in Pairs

image

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
      ListNode curNode = head, initHead = null, tailNode = null;
      if(curNode == null || curNode.next == null) return head;
      while(curNode != null && curNode.next != null) {
        ListNode desNode = curNode.next.next;
        curNode.next.next = curNode;
        if(tailNode == null) initHead = curNode.next;
        else tailNode.next = curNode.next;
        tailNode = curNode;
        curNode = desNode;
      }
      if(curNode == null) tailNode.next = null;
      else tailNode.next = curNode;
      return initHead;
    }
}
This post is licensed under CC BY 4.0 by the author.