Problem statement: Reverse a LinkedList in java !
- class Node5 {
- Node5 next;
- int data;
- Node5(int data) {
- this.data = data;
- }
- } // end of Node5
- public class ReverseLinkedList {
- Node5 head;
- public static void main(String[] args) {
- ReverseLinkedList l = new ReverseLinkedList();
- l.add(3);
- l.add(5);
- l.add(8);
- l.add(9);
- l.print(l.head);
- l.reverse();
- System.out.println("\nafter reverse linked list");
- l.print(l.head);
- } // end of main()
- // add the element in LinkedList
- public void add(int data) {
- Node5 next = new Node5(data);
- if (head == null) {
- head = next;
- return;
- }
- Node5 last = head;
- while (last.next != null) {
- last = last.next;
- }
- last.next = next;
- } // end of add()
- // print the LinkedList
- void print(Node5 next) {
- Node5 temp = next;
- while (temp != null) {
- System.out.print(temp.data + "-->");
- temp = temp.next;
- }
- } // end of print()
- // reverse the LinkedList
- Node5 reverse() {
- Node5 prev = null;
- Node5 current = head;
- Node5 next = null;
- while (current != null) {
- next = current.next;
- current.next = prev;
- prev = current;
- current = next;
- }
- head = prev;
- return head;
- } // end of reverse()
- } //end of ReverseLinkedList
Output:
3-->5-->8-->9-->
after reverse linked list
9-->8-->5-->3-->
No comments:
Post a Comment