24. Swap Nodes in Pairs
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.)
1
2
3
4
| Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
|

1
2
3
4
5
6
7
8
9
| Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
|
Constraints:
- The number of nodes in the list is in the range [0, 100].
- 0 <= Node.val <= 100
Solution#
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
28
29
30
31
| /**
* 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 dummy = new ListNode(0);
dummy.next = head;
ListNode runner = dummy;
while (runner.next != null && runner.next.next != null) {
ListNode r1 = runner.next;
ListNode r2 = runner.next.next;
runner.next = r2;
r1.next = r2.next;
r2.next = r1;
runner = runner.next.next;
}
return dummy.next;
}
}
|