Tuesday, May 1, 2018

LinkedList implementation

Problem statement: LinkedList implementation in java !!
  1. class A {
  2. A n;
  3. int data;
  4. A(int data) {
  5. this.data = data;
  6. }
  7. }
  8. public class LinkedList {
  9. A head;

  10. /*public static void main(String[] args) {

  11. add(1);
  12. add(2);
  13. print(head);
  14. */

  15. /*
  16. A head = new A(1);
  17. A h1 = new A(2);
  18. A h2 = new A(3);
  19. A h3 = new A(4);
  20. A h4 = new A(5);
  21. A h5 = new A(6);

  22. head.n=h1; h1.n=h2; h2.n=h3;h3.n=h4;h4.n=h5;//h5.n=null;

  23. print(head);

  24. /*A head = new A();
  25. head.data=1;
  26. head.n=null;

  27. A h1 = new A();
  28. h1.data=2;
  29. h1.n=null;

  30. head.n=h1;

  31. A h2 = new A();
  32. h2.data=3;
  33. h2.n=null;

  34. h1.n=h2;

  35. A h3 = new A();
  36. h3.data=4;
  37. h3.n=null;

  38. h2.n=h3;

  39. A h4 = new A();
  40. h4.data=5;
  41. h4.n=null;

  42. h3.n=h4;
  43. */
  44. /* System.out.println(head.data); h.data;
  45. System.out.println(head.n.data);h=h.n; h.data;
  46. System.out.println(head.n.n.data); h=h.n.n;h.data;
  47. System.out.println(head.n.n.n.data);h=h.n.n.n;h.data;
  48. System.out.println(head.n.n.n.n.data);h=h.n.n.n.n;h.data;

  49. print(head);
  50. */
  51. //}

  52. // print the LinkedList
  53. public  void print(A head){
  54. A temp=head;
  55. while(temp!=null){
  56. System.out.println(temp.data);
  57. temp=temp.n;
  58. }
  59. }

  60. // add the element in LinkedList
  61. public void add(int data) {
  62. A new_node = new A(data);

  63. if (head == null) {
  64. head = new_node;
  65. return;
  66. }
  67. A last = head;
  68. while (last.n != null) {
  69. last = last.n;
  70. }
  71. last.n = new_node;
  72. }

  73. // reverse the LinkedList
  74. A reverse() {
  75. A prev = null;
  76. A current = head;
  77. A next = null;
  78. while (current != null) {
  79. next = current.n;
  80. current.n = prev;
  81. prev = current;
  82. current = next;
  83. }
  84. head = prev;
  85. return head;
  86. }
  87. }
MainUser class:

  1. public class MyLinkedList {

  2. public static void main(String[] args) {
  3. LinkedList l = new LinkedList();
  4. l.add(1);
  5. l.add(2);

  6. l.print(l.head);

  7. l.reverse();
  8. System.out.println("-----------");
  9. l.print(l.head);
  10. }
  11. }
Output:
1
2
-----------
2
1

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...