forked from Knackie/algorithmshacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswapTwoNumberInLL.java
59 lines (46 loc) · 1.39 KB
/
swapTwoNumberInLL.java
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
57
58
59
package linkedList;
public class swapTwoNumberInLL {
// Definition for singly-linked list.
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static void printLL(ListNode head) {
ListNode cur=head;
while(cur!=null) {
System.out.print(cur.val +" --> ");
cur=cur.next;
}
System.out.println("end");
}
public static ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prev=dummy;
while(prev.next !=null && prev.next.next !=null){
ListNode current=prev.next;
ListNode forward=current.next;
ListNode temp=forward.next;
prev.next=forward;
forward.next=current;
current.next=temp;
prev=current;
}
return dummy.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head=new ListNode(1);
head.next=new ListNode(8);
head.next.next=new ListNode(3);
head.next.next.next=new ListNode(4);
head.next.next.next.next=new ListNode(5);
head.next.next.next.next.next=new ListNode(6);
printLL(head);
swapPairs(head);
printLL(head);
}
}