Skip to content

Commit 56d7796

Browse files
author
Dhananjay Nagargoje
committed
2 pointer
1 parent a1bb0cf commit 56d7796

File tree

6 files changed

+70
-3
lines changed

6 files changed

+70
-3
lines changed
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,71 @@
11
package problems.patterns.onlinkedlistreversal;
22

3-
public class ReverseLinkedList {
3+
class ListNode {
4+
int value = 0;
5+
ListNode next;
6+
7+
ListNode(int value) {
8+
this.value = value;
9+
}
410
}
11+
12+
class ReverseLinkedList {
13+
14+
public static ListNode reverse(ListNode head) {
15+
if (head == null || head.next == null) return head;
16+
17+
ListNode prev = null;
18+
ListNode cur = head;
19+
20+
while (cur != null) {
21+
ListNode rest = cur.next;
22+
cur.next = prev;
23+
prev = cur;
24+
cur = rest;
25+
}
26+
return prev;
27+
}
28+
public static ListNode reverse(ListNode head, int p, int q) {
29+
if (head == null || head.next == null) return head;
30+
if (p == 1 && q == 1) return head;
31+
int cnt = 1;
32+
ListNode rethead = head;
33+
ListNode prevh = null;
34+
35+
while (cnt!=p) {
36+
prevh = head;
37+
head = head.next;
38+
cnt++;
39+
}
40+
ListNode prev = null;
41+
ListNode cur = head;
42+
ListNode rest = cur.next;
43+
ListNode temphead = head;
44+
while (cnt<= q && cur != null) {
45+
rest = cur.next;
46+
cur.next = prev;
47+
prev = cur;
48+
cur = rest;
49+
cnt++;
50+
}
51+
prevh.next = prev;
52+
temphead.next = rest;
53+
return prevh;
54+
}
55+
56+
public static void main(String[] args) {
57+
ListNode head = new ListNode(2);
58+
head.next = new ListNode(4);
59+
head.next.next = new ListNode(6);
60+
head.next.next.next = new ListNode(8);
61+
head.next.next.next.next = new ListNode(10);
62+
63+
// ListNode result = ReverseLinkedList.reverse(head);
64+
ListNode result = ReverseLinkedList.reverse(head, 2, 4);
65+
System.out.print("Nodes of the reversed LinkedList are: ");
66+
while (result != null) {
67+
System.out.print(result.value + " ");
68+
result = result.next;
69+
}
70+
}
71+
}

Diff for: src/main/java/problems/patterns/ontwopointerstrategy/BinaryArraySorting.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package problems.ontwopointerstrategy;
1+
package problems.patterns.ontwopointerstrategy;
22

33
public class BinaryArraySorting {
44
/**

Diff for: src/main/java/problems/patterns/ontwopointerstrategy/TripLetWithZeroSum.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package problems.ontwopointerstrategy;
1+
package problems.patterns.ontwopointerstrategy;
22

33
import java.util.Arrays;
44

0 commit comments

Comments
 (0)