-
Notifications
You must be signed in to change notification settings - Fork 0
/
Swap Nodes in Pairs
33 lines (33 loc) · 949 Bytes
/
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
28
29
30
31
32
33
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(head == null || head.next == null) return head;
ListNode temp = head;
ListNode current = head;
ListNode result = head.next;
while(current != null && current.next != null)
{
temp = current.next.next;
current.next.next = current;
if(temp != null && temp.next != null){
current.next = temp.next;
}
else{ //odd elements
current.next = temp;
}
current = temp; //next pair of nodes
}
return result;
}
}