public class SinglyLinkedList {
private ListNode head;
private static class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
this.next = null;
}
}
// printing singly linked list
public void displayList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
// Reverse the linked list
public ListNode reverse(ListNode head) {
if (head == null) {
return head;
}
ListNode current = head;
ListNode previous = null;
ListNode next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
public static void main(String[] args) {
// creating nodes
SinglyLinkedList sl = new SinglyLinkedList();
sl.head = new ListNode(10);
ListNode second = new ListNode(1);
ListNode third = new ListNode(2);
ListNode fourth = new ListNode(3);
// connecting nodes together
sl.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
sl.displayList(sl.head);
SinglyLinkedList.ListNode reverse = sl.reverse(sl.head);
sl.displayList(reverse);
}
}
No comments:
Post a Comment