-
Notifications
You must be signed in to change notification settings - Fork 6
/
DesignLinkedList.java
135 lines (98 loc) · 2.66 KB
/
DesignLinkedList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package com.shivaprasad.january.day10;
//Include only Node class code and methods(except main) in final submission.
//Problem:https://leetcode.com/problems/design-linked-list/
public class DesignLinkedList {
class Node
{
int val;
Node next;
Node(int val)
{
this.val = val;
}
}
Node dummyNode;
int size;
public DesignLinkedList() {
dummyNode = new Node(-1);
size = 0;
}
public int get(int index) {
if(index >= size)
return -1;
Node currNode = dummyNode;
for(int i=0;i<=index;i++)
{
currNode = currNode.next;
}
return currNode.val;
}
public void addAtHead(int val) {
Node head = new Node(val);
head.next = dummyNode.next;
dummyNode.next = head;
size++;
}
public void addAtTail(int val) {
Node curr = dummyNode;
Node tail = new Node(val);
for(int i=0;i<size;i++)
{
curr = curr.next;
}
curr.next = tail;
size++;
}
public void addAtIndex(int index, int val) {
if(index > size)
return;
Node curr = dummyNode;
Node newNode = new Node(val);
for(int i=0;i<index;i++)
{
curr = curr.next;
}
newNode.next = curr.next;
curr.next = newNode;
size++;
}
public void deleteAtIndex(int index) {
if(index >= size)
return;
Node curr = dummyNode;
for(int i=0;i<index;i++)
{
curr = curr.next;
}
curr.next = curr.next.next;
size--;
}
//DON'T INCLUDE THIS IN MAIN SUBMISSION
//Creating this method just for output tracking.
public void display()
{
Node curr =dummyNode.next;
while(curr!=null)
{
System.out.print(curr.val+" ");
curr = curr.next;
}
}
//Creating this method only for testing. DON'T INCLUDE THIS IN FINAL SUBMISSION.
public static void main(String[] args) {
DesignLinkedList obj = new DesignLinkedList();
System.out.print("get 1: "+ obj.get(1));
obj.addAtHead(5);
System.out.println("\n\nLinked List after addAtHead");
obj.display();
obj.addAtTail(9);
System.out.println("\n\nLinked List after addAtTail");
obj.display();
obj.addAtIndex(1,11);
System.out.println("\n\nLinked List after addAtIndex");
obj.display();
obj.deleteAtIndex(1);
System.out.println("\n\nLinked List after deleteAtIndex");
obj.display();
}
}