-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswapPairs.java
More file actions
28 lines (26 loc) · 794 Bytes
/
swapPairs.java
File metadata and controls
28 lines (26 loc) · 794 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
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode current = head;
ListNode previous = null;
int index = 0;
while(current != null){
if(index % 2 == 0 && current.next != null){
ListNode temp = current.next;
if(previous != null){
previous.next = current.next;
current.next = current.next.next;
temp.next = current;
}else{
current.next = current.next.next;
temp.next = current;
head = temp;
}
index += 2;
}else{
index++;
}
previous = current;
current = current.next;
}
return head;
}