Tuesday, May 1, 2018

Reverse a LinkedList

Problem statement: Reverse a LinkedList in java !
  1. class Node5 {
  2. Node5 next;
  3. int data;

  4. Node5(int data) {
  5. this.data = data;
  6. }
  7. } // end of Node5

  8. public class ReverseLinkedList {

  9. Node5 head;

  10. public static void main(String[] args) {
  11. ReverseLinkedList l = new ReverseLinkedList();
  12. l.add(3);
  13. l.add(5);
  14. l.add(8);
  15. l.add(9);
  16. l.print(l.head);
  17. l.reverse();
  18. System.out.println("\nafter reverse linked list");
  19. l.print(l.head);
  20. } // end of main()

  21. // add the element in LinkedList
  22. public void add(int data) {
  23. Node5 next = new Node5(data);
  24. if (head == null) {
  25. head = next;
  26. return;
  27. }
  28. Node5 last = head;
  29. while (last.next != null) {
  30. last = last.next;
  31. }
  32. last.next = next;
  33. } // end of add()

  34. // print the LinkedList
  35. void print(Node5 next) {
  36. Node5 temp = next;
  37. while (temp != null) {
  38. System.out.print(temp.data + "-->");
  39. temp = temp.next;
  40. }
  41. } // end of print()

  42. // reverse the LinkedList
  43. Node5 reverse() {
  44. Node5 prev = null;
  45. Node5 current = head;
  46. Node5 next = null;
  47. while (current != null) {
  48. next = current.next;
  49. current.next = prev;
  50. prev = current;
  51. current = next;
  52. }
  53. head = prev;
  54. return head;
  55. } // end of reverse()
  56. } //end of ReverseLinkedList 
Output: 
3-->5-->8-->9-->
after reverse linked list
9-->8-->5-->3-->

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...