Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3886984

Browse files
LC#206 reverse a given linkedlist, iterative & recursive approach
1 parent 55cce41 commit 3886984

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package LinkedList;
2+
3+
public class ReverseLinkedList206 {
4+
5+
public class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode() {
10+
}
11+
12+
ListNode(int val) {
13+
this.val = val;
14+
}
15+
16+
ListNode(int val, ListNode next) {
17+
this.val = val;
18+
this.next = next;
19+
}
20+
}
21+
22+
// using recursion
23+
public ListNode reverseList(ListNode head) {
24+
return recursiveReverse(head);
25+
}
26+
27+
private ListNode recursiveReverse(ListNode head) {
28+
29+
if (head == null || head.next == null)
30+
return head;
31+
32+
ListNode newHead = recursiveReverse(head.next);
33+
34+
head.next.next = head;
35+
head.next = null;
36+
37+
return newHead;
38+
}
39+
40+
// using iterative approach
41+
public ListNode reverseListIterative(ListNode head) {
42+
43+
if (head == null || head.next == null)
44+
return head;
45+
46+
ListNode prev = head;
47+
ListNode curr = head.next;
48+
ListNode nextNode = head.next.next;
49+
prev.next = null; // head node pointing to null as it will be tail at the end
50+
51+
while (curr.next != null) {
52+
curr.next = prev;
53+
prev = curr;
54+
curr = nextNode;
55+
nextNode = curr.next;
56+
}
57+
58+
// pointing last node to second last node
59+
curr.next = prev;
60+
61+
return curr;
62+
}
63+
64+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /