public class ReverseLinkedList {
private ListNode head;
public ReverseLinkedList() {
head = new ListNode(0, null);
ListNode prev = head, temp;
for (int i = 1; i <= 5; i++) {
temp = new ListNode(i, null);
prev.next = temp;
prev = temp;
}
}
private void printLinkedList() {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.val + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
ReverseLinkedList application = new ReverseLinkedList();
application.printLinkedList();
application.reverseList();
application.printLinkedList();
}
public void reverseList() {
if (head == null || head.next == null) {
return;
}
ListNode previousNode = null;
ListNode currentNode = head;
ListNode nextNode;
while (currentNode != null) {
nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
head = previousNode;
}
private class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}