-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathSwapAlternate.java
More file actions
54 lines (44 loc) · 1.16 KB
/
SwapAlternate.java
File metadata and controls
54 lines (44 loc) · 1.16 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
package LinkedLists;
/**
* Author - archit.s
* Date - 19/10/18
* Time - 8:48 PM
*/
public class SwapAlternate {
public ListNode swapPairs(ListNode A) {
if(A == null || A.next == null){
return A;
}
ListNode head = null;
ListNode last = null;
ListNode current = A;
ListNode next;
while(current!=null && current.next !=null){
ListNode temp = current.next;
next = temp.next;
if(head == null){
head = temp;
last = temp;
last.next = current;
}
else{
last.next = temp;
last = last.next;
last.next = current;
}
last = last.next;
current = next;
}
if(last!=null){
last.next = current;
}
return head;
}
public static void main(String[] args) {
ListNode r = new ListNode(1);
r.next = new ListNode(2);
r.next.next = new ListNode(3);
r.next.next.next = new ListNode(4);
System.out.println(new SwapAlternate().swapPairs(r));
}
}