-
Notifications
You must be signed in to change notification settings - Fork 820
/
ReverseLinkedList.java
56 lines (50 loc) · 1.28 KB
/
ReverseLinkedList.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
/* (C) 2024 YourCompanyName */
package linked_list;
/** Created by gouthamvidyapradhan on 24/02/2017. Reverse a singly linked list. */
public class ReverseLinkedList {
private ListNode newHead;
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
// node5.next = node6;
ListNode newNode = new ReverseLinkedList().reverseList(node1);
System.out.println(newNode.val);
}
public ListNode reverseList(ListNode head) {
if (head == null) return null;
else if (head.next == null) return head;
reverse(head).next = null;
return newHead;
}
private ListNode reverse(ListNode head) {
if (head.next == null) {
newHead = head;
return head;
}
ListNode node = reverse(head.next);
node.next = head;
return head;
}
}