-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseLinkedList.java
executable file
·50 lines (43 loc) · 1.42 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
public class ReverseLinkedList {
private static ListNode returnNode = null;
public static ListNode reverseList(ListNode head) {
reverse(head);
return returnNode;
}
static ListNode reverse(ListNode head){
if(head == null || head.next == null){
returnNode = head;
return head;
}
ListNode node = reverse(head.next);
node.next = head;
head.next = null;
return head;
}
public static void main(String[] args) {
int []arr = {1,2,3,4,5};
ListNode head = createLinkedList(arr);
ListNode reverse = reverseList(head);
while(reverse!=null){
System.out.print(reverse.val+" ");
reverse = reverse.next;
}
}
private static ListNode createLinkedList(int[] array){
ListNode head = new ListNode(array[0]);
ListNode previous = head;
for(int i=1; i<array.length ; i++){
ListNode newNode = new ListNode(array[i]);
previous.next = newNode;
previous = newNode;
}
return head;
}
}
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}