-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesign Linked List
87 lines (80 loc) · 1.85 KB
/
Design Linked List
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
class MyLinkedList {
Node head;
int length;
public class Node{
int val;
Node next;
Node(int val){
this.val=val;
}
}
public MyLinkedList(){
this.head=null;
int length=0;
}
public int get(int index) {
if(index >= length)
return -1;
int counter = 0;
Node temp = head;
while(counter < index) {
counter++;
temp = temp.next;
}
return temp.val;
}
public void addAtHead(int val) {
Node newnew = new Node(val);
newnew.next = head;
head = newnew;
length++;
}
public void addAtTail(int val) {
if(head == null) {
addAtHead(val);
}else {
Node temp = head;
while(temp.next != null)
temp = temp.next;
Node newnew = new Node(val);
temp.next = newnew;
length++;
}
}
public void addAtIndex(int index, int val) {
if(index > length)
return;
if(index == 0)
addAtHead(val);
else {
int counter = 1;
Node temp = head;
while(counter < index) {
temp = temp.next;
counter++;
}
Node newnew = new Node(val);
Node next = temp.next;
temp.next = newnew;
newnew.next = next;
length++;
}
}
public void deleteAtIndex(int index) {
if(index >= length)
return;
if(index == 0) {
head = head.next;
length--;
}else {
int counter = 1;
Node temp = head;
while(counter < index) {
counter++;
temp = temp.next;
}
temp.next = temp.next.next;
length--;
}
}
}