From eb4387088b15c49ff98952abde8e887908db96b3 Mon Sep 17 00:00:00 2001 From: CodeGeek109 <91720037+CodeGeek109@users.noreply.github.com> Date: Sun, 31 Oct 2021 14:20:57 +0530 Subject: [PATCH] Create Remove first in Linked List.java --- Remove first in Linked List.java | 79 ++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Remove first in Linked List.java diff --git a/Remove first in Linked List.java b/Remove first in Linked List.java new file mode 100644 index 0000000..8368bdf --- /dev/null +++ b/Remove first in Linked List.java @@ -0,0 +1,79 @@ +import java.io.*; +import java.util.*; + +public class Main { + 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(); + } + + public void removeFirst(){ + if(size==0) + { + System.out.println("List is empty"); + + } + else if(size==1) + { + head=tail=null; + size=0; + } + else + { + head=head.next; + size--; + } + } + } + + 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(); + } + } +}