-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswappairs.java
More file actions
executable file
·56 lines (51 loc) · 1.42 KB
/
swappairs.java
File metadata and controls
executable file
·56 lines (51 loc) · 1.42 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Neel_Kapadia
*/
public class swappairs {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = head;
ListNode curr = head;
ListNode next = head.next;
head = next;
boolean flag = false;
while (curr != null) {
curr.next = next.next;
next.next = curr;
if(flag == false){
prev = next;
flag =true;
}
else{
prev.next = next;
}
prev = curr;
curr = curr.next;
if (curr == null || curr.next == null) {
return head;
}
next = next.next.next;
}
return head;
}
public static void main(String[] args) {
ListNode x = new ListNode(1);
x.next = new ListNode(2);
x.next.next = new ListNode(3);
x.next.next.next = new ListNode(4);
swappairs s = new swappairs();
ListNode a = s.swapPairs(x);
while (a != null) {
System.out.println(a.val);
a = a.next;
}
}
}