-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverseLinkedList.java
48 lines (42 loc) · 1.06 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
package data_structures.arrays;
public class ReverseLinkedList{
Node head;
static class Node{
int value;
Node next;
Node(int value){
this.value = value;
next = null;
}
}
Node reverse(Node head){
Node prev = null;
Node next;
while (head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
static void printList(Node node){
System.out.print("HEAD -> ");
while (node != null) {
System.out.print(node.value + " -> ");
node = node.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
ReverseLinkedList list = new ReverseLinkedList();
list.head = new Node(23);
list.head.next = new Node(435);
list.head.next.next = new Node(76);
list.head.next.next.next = new Node(-99);
list.head.next.next.next.next = new Node(12);
printList(list.head);
list.head = list.reverse(list.head);
printList(list.head);
}
}