-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
37 lines (33 loc) · 905 Bytes
/
Solution.java
File metadata and controls
37 lines (33 loc) · 905 Bytes
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
32
33
34
35
36
37
package leetcode._24_;
import leetcode.common.ListNode;
/**
* 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 temp = head.next;
head.next = temp.next;
temp.next = head;
head = temp;
ListNode frontNode = head.next.next;
ListNode backNode = head.next;
while (frontNode != null && frontNode.next != null) {
temp = frontNode.next;
backNode.next = temp;
frontNode.next = temp.next;
temp.next = frontNode;
backNode = backNode.next;
frontNode = frontNode.next;
backNode = backNode.next;
}
return head;
}
}