-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC707.java
More file actions
85 lines (72 loc) · 1.88 KB
/
Copy pathLC707.java
File metadata and controls
85 lines (72 loc) · 1.88 KB
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
class MyLinkedList {
class Node {
int val;
Node next;
public Node() {
}
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
}
Node dummy;
int length;
public MyLinkedList() {
dummy = new Node();
length = 0;
}
public int get(int index) {
if (index < 0 || index >= length) {
return -1;
}
Node curNode = dummy.next;
while (index-- > 0) {
curNode = curNode.next;
}
return curNode.val;
}
public void addAtHead(int val) {
dummy.next = new Node(val, dummy.next);
length++;
}
public void addAtTail(int val) {
Node curNode = dummy;
while (curNode.next != null) {
curNode = curNode.next;
}
curNode.next = new Node(val, null);
length++;
}
public void addAtIndex(int index, int val) {
if (index > length) {
return;
} else if (index == length) {
addAtTail(val);
} else if (index <= 0) {
addAtHead(val);
} else {
Node curNode = dummy;
while (index-- > 0) {
curNode = curNode.next;
}
curNode.next = new Node(val, curNode.next);
length++;
}
}
public void deleteAtIndex(int index) {
if (index < length) {
Node curNode = dummy;
while (index-- > 0) {
curNode = curNode.next;
}
curNode.next = curNode.next.next;
length--;
}
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList(); int param_1 = obj.get(index);
* obj.addAtHead(val); obj.addAtTail(val); obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/