Description
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)
Example 1:
1Input: head = [1,2,3,4]
2Output: [2,1,4,3]
Example 2:
1Input: head = []
2Output: []
Example 3:
1Input: head = [1]
2Output: [1]
Constraints:
- The number of nodes in the list is in the range
[0, 100]. 0 <= Node.val <= 100
Solution
This problem requires node manipulations in linked list. We have to be careful with the sequence of operations because it can result in very different result.
1class Solution {
2 public ListNode swapPairs(ListNode head) {
3 if (head == null || head.next == null) {
4 return head;
5 }
6 ListNode current = head;
7 ListNode newHead = head.next;
8 ListNode prev = null;
9 ListNode next;
10 while (current != null && current.next != null) {
11 next = current.next;
12 current.next = next.next;
13 next.next = current;
14 if (prev != null) {
15 prev.next = next;
16 }
17 prev = current;
18 current = current.next;
19 }
20 return newHead;
21 }
22}


Comments