From f81bffa09c304906e2a09fe28f94d67ac97cf74b Mon Sep 17 00:00:00 2001 From: agampreetsingh Date: Tue, 29 Oct 2019 00:53:05 +0530 Subject: [PATCH] Adding LinkedList --- Data Structures/LinkedList/LinkedList.java | 160 +++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 Data Structures/LinkedList/LinkedList.java diff --git a/Data Structures/LinkedList/LinkedList.java b/Data Structures/LinkedList/LinkedList.java new file mode 100644 index 0000000..ec35c50 --- /dev/null +++ b/Data Structures/LinkedList/LinkedList.java @@ -0,0 +1,160 @@ +package LinkedList; + +public class LinkedList { + + private Node head; + + private int size; + + private Node tail; + + public void add(int number) { + if(this.size==0) { + Node node = new Node(); + node.setNumber(number); + node.setNext(null); + this.head=node; + this.tail=this.head; + this.size++; + return; + } + Node node = new Node(); + node.setNumber(number); + node.setNext(null); + this.tail.setNext(node); + this.tail=node; + this.size++; + } + + + public void addFirst(int number) { + this.addFirst(this.head,number); + } + + public void addFirst(Node head, int number) { + Node node = new Node(); + node.setNumber(number); + node.setNext(head); + this.head=node; + } + + + + public void display() { + this.display(this.head); + } + + + public void display(Node node) { + while(node.getNext()!=null) { + System.out.print(node.getNumber()+" "); + node=node.getNext(); + } + + } + + public void addAt(int index, int number) throws Exception { + if(this.size=this.size) { + throw new Exception("Invalid Arguments"); + } + + Node temp = this.head; + for(int i=0;ithis.size-1) { + throw new Exception("Invalid Index"); + } + + if(this.size==1) { + Node rv = head; + this.head = null; + this.size--; + return rv; + } + else if(index==0) { + Node rv = this.head; + this.head=this.head.getNext(); + this.size--; + return rv; + } + + int i=0; + Node curr = head.getNext(); + Node prev = head; + while(i!=index-1) { + prev = curr; + curr = curr.getNext(); + i++; + } + prev.setNext(curr.getNext()); + this.size--; + return curr; + } + + + + + + + +} +