Custom Linked list in java add and push element



class LL1 {
Node head;

class Node {
int data;
Node next;

Node(int data) {
this.data = data;
next = null;
}
}

public void addDataFirst(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}

public void addDataLast(int data) {
Node newNode = new Node(data);
if (head == null)
head = newNode;
else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}

public void printList() {
Node temp = head;
while (temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}

void reverseL() {
reverseList(head);
}
void reverseList(Node node) {
Node prev = null;
        Node current = node;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        head = prev;
}
}

public class LinedListFirst {

public static void main(String[] args) {
LL1 al = new LL1();

al.addDataFirst(10);
al.addDataFirst(12);
al.addDataFirst(14);
al.addDataFirst(18);

al.addDataLast(10);
al.addDataLast(12);
al.addDataLast(14);
al.addDataLast(18);

al.printList();
  System.out.println();
  al.reverseL();
  al.printList();
}

}

Post a Comment

Previous Post Next Post