-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseList.java
More file actions
52 lines (41 loc) · 892 Bytes
/
reverseList.java
File metadata and controls
52 lines (41 loc) · 892 Bytes
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
//reverse a linked list
class Node{
Node(int val){
value = val;
next = null;
}
public int value;
public Node next;
}
public class reverseList{
static Node reverse(Node head){
if(head == null || head.next == null)
return head;
Node second = head.next;
head.next = null;
Node rest = reverse(second);
second.next = head;
return rest;
}
static void print(Node head){
Node temp;
temp = head;
while(temp.next != null){
System.out.print(temp.value + "->");
temp = temp.next;
}
System.out.print(temp.value);
System.out.println();
}
public static void main(String[] args){
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
System.out.println("Before reversal");
print(head);
head = reverse(head);
System.out.println("After reversal");
print(head);
}
}