From 7a0b3780e1a4b25d6e9bc5d43ef3d072ededdb73 Mon Sep 17 00:00:00 2001 From: saitejomaayi <149611088+saitejomaayi@users.noreply.github.com> Date: Thu, 24 Oct 2024 06:52:43 -0400 Subject: [PATCH] Design-2 Implemented HashMap and Queue as a stack --- HashMap.java | 78 +++++++++++++++++++++++++++++++++++++++++++++++ QueueAsStack.java | 46 ++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 HashMap.java create mode 100644 QueueAsStack.java diff --git a/HashMap.java b/HashMap.java new file mode 100644 index 00000000..e54acb3e --- /dev/null +++ b/HashMap.java @@ -0,0 +1,78 @@ +class MyHashMap { + + class Node { + int key; + int value; + Node next; + public Node(int key, int value){ + this.key=key; + this.value=value; + } + } + Node[] s; + int bucket=10000; + public MyHashMap() { + + this.bucket=10000; + this.s=new Node[bucket]; + } + int getHash(int key){ + return key % bucket; + } + Node getPrev(Node head, int key){ + Node prev=null; + Node curr=head; + if(curr!=null && curr.key!=key){ + prev=curr; + curr=curr.next; + } + return prev; + } + public void put(int key, int value) { + int idx=getHash(key); + if(s[idx]==null) + s[idx]=new Node(-1,-1); + Node prev=getPrev(s[idx],key); + if(prev.next==null) + prev.next= new Node(key,value); + else{ + prev.next.value=value; + } + } + + public int get(int key) { + int idx=getHash(key); + if(s[idx]==null){ + return -1; + } + Node prev=getPrev(s[idx],key); + if(prev.next==null){ + return -1; + } + + return prev.next.value; + } + + public void remove(int key) { + int idx=getHash(key); + if(s[idx]==null){ + return; + } + Node prev=getPrev(s[idx],key); + if(prev.next==null){ + return; + } + Node cur=prev.next; + prev.next=cur.next; + cur=null; + + } +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * MyHashMap obj = new MyHashMap(); + * obj.put(key,value); + * int param_2 = obj.get(key); + * obj.remove(key); + */ \ No newline at end of file diff --git a/QueueAsStack.java b/QueueAsStack.java new file mode 100644 index 00000000..9ea19e3a --- /dev/null +++ b/QueueAsStack.java @@ -0,0 +1,46 @@ +class MyQueue { + Stack in; + Stack out; + public MyQueue() { + this.in= new Stack<>(); + this.out= new Stack<>(); + } + + public void push(int x) { + in.push(x); + } + + public int pop() { + if(out.isEmpty()){ + while(!in.isEmpty()){ + out.push(in.pop()); + } + } + return out.pop(); + } + + public int peek() { + if(out.isEmpty()){ + while(!in.isEmpty()){ + out.push(in.pop()); + } + } + return out.peek(); + } + + public boolean empty() { + if(in.isEmpty() && out.isEmpty()) + return true; + else + return false; + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ \ No newline at end of file