Friday, February 4, 2022

Remove First In Linkedlist

 


import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
addLast 10
addLast 20
addLast 30
display
removeFirst
size
addLast 40
addLast 50
removeFirst
display
size
removeFirst
removeFirst
removeFirst
removeFirst
quit
*/
public class Remove_FIrst_In_LinkedList {
public static class Node {
int data;
Node next;
}

public static class LinkedList {
Node head;
Node tail;
int size;

void addLast(int val) {
Node temp = new Node();
temp.data = val;
temp.next = null;

if (size == 0) {
head = tail = temp;
} else {
tail.next = temp;
tail = temp;
}

size++;
}

public int size() {
return size;
}

public void display() {
for (Node temp = head; temp != null; temp = temp.next) {
System.out.print(temp.data + " ");
}
System.out.println();
}

// write your code here
public void removeFirst() {
if (head != null) {
head = head.next;
size--;
} else {
System.out.println("List is empty");
}
}

}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LinkedList list = new LinkedList();

String str = br.readLine();
while (str.equals("quit") == false) {
if (str.startsWith("addLast")) {
int val = Integer.parseInt(str.split(" ")[1]);
list.addLast(val);
} else if (str.startsWith("size")) {
System.out.println(list.size());
} else if (str.startsWith("display")) {
list.display();
} else if (str.startsWith("removeFirst")) {
list.removeFirst();
}
str = br.readLine();
}
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...