Problem statement: LinkedList implementation in java !!
- class A {
- A n;
- int data;
- A(int data) {
- this.data = data;
- }
- }
- public class LinkedList {
- A head;
- /*public static void main(String[] args) {
- add(1);
- add(2);
- print(head);
- */
- /*
- A head = new A(1);
- A h1 = new A(2);
- A h2 = new A(3);
- A h3 = new A(4);
- A h4 = new A(5);
- A h5 = new A(6);
- head.n=h1; h1.n=h2; h2.n=h3;h3.n=h4;h4.n=h5;//h5.n=null;
- print(head);
- /*A head = new A();
- head.data=1;
- head.n=null;
- A h1 = new A();
- h1.data=2;
- h1.n=null;
- head.n=h1;
- A h2 = new A();
- h2.data=3;
- h2.n=null;
- h1.n=h2;
- A h3 = new A();
- h3.data=4;
- h3.n=null;
- h2.n=h3;
- A h4 = new A();
- h4.data=5;
- h4.n=null;
- h3.n=h4;
- */
- /* System.out.println(head.data); h.data;
- System.out.println(head.n.data);h=h.n; h.data;
- System.out.println(head.n.n.data); h=h.n.n;h.data;
- System.out.println(head.n.n.n.data);h=h.n.n.n;h.data;
- System.out.println(head.n.n.n.n.data);h=h.n.n.n.n;h.data;
- print(head);
- */
- //}
- // print the LinkedList
- public void print(A head){
- A temp=head;
- while(temp!=null){
- System.out.println(temp.data);
- temp=temp.n;
- }
- }
- // add the element in LinkedList
- public void add(int data) {
- A new_node = new A(data);
- if (head == null) {
- head = new_node;
- return;
- }
- A last = head;
- while (last.n != null) {
- last = last.n;
- }
- last.n = new_node;
- }
- // reverse the LinkedList
- A reverse() {
- A prev = null;
- A current = head;
- A next = null;
- while (current != null) {
- next = current.n;
- current.n = prev;
- prev = current;
- current = next;
- }
- head = prev;
- return head;
- }
- }
- public class MyLinkedList {
- public static void main(String[] args) {
- LinkedList l = new LinkedList();
- l.add(1);
- l.add(2);
- l.print(l.head);
- l.reverse();
- System.out.println("-----------");
- l.print(l.head);
- }
- }
Output:
1
2
-----------
2
1
1
2
-----------
2
1
No comments:
Post a Comment