-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0707-design-linked-list.swift
105 lines (92 loc) · 2.29 KB
/
0707-design-linked-list.swift
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
/**
* Question Link: https://leetcode.com/problems/design-linked-list/
*/
class ListNode {
var val: Int
var next: ListNode?
var prev: ListNode?
init(_ val: Int) {
self.val = val
}
}
class MyLinkedList {
var left: ListNode
var right: ListNode
init() {
self.left = ListNode(-1)
self.right = ListNode(-1)
left.next = right
right.prev = left
}
func get(_ index: Int) -> Int {
var cur = left.next
var index = index
while cur != nil && index > 0 {
cur = cur?.next
index -= 1
}
if cur != nil && cur !== right && index == 0 {
return cur!.val
} else {
return -1
}
}
func addAtHead(_ val: Int) {
let node = ListNode(val)
let next = left.next
let prev = left
prev.next = node
next?.prev = node
node.next = next
node.prev = prev
}
func addAtTail(_ val: Int) {
let node = ListNode(val)
let next = right
let prev = right.prev
prev?.next = node
next.prev = node
node.next = next
node.prev = prev
}
func addAtIndex(_ index: Int, _ val: Int) {
var cur = left.next
var index = index
while cur != nil && index > 0 {
cur = cur?.next
index -= 1
}
if cur != nil && index == 0 {
let node = ListNode(val)
let next = cur
let prev = cur?.prev
prev?.next = node
next?.prev = node
node.next = next
node.prev = prev
}
}
func deleteAtIndex(_ index: Int) {
var cur = left.next
var index = index
while cur != nil && index > 0 {
cur = cur?.next
index -= 1
}
if cur != nil && cur !== right && index == 0 {
let next = cur?.next
let prev = cur?.prev
prev?.next = next
next?.prev = prev
}
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* let obj = MyLinkedList()
* let ret_1: Int = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index, val)
* obj.deleteAtIndex(index)
*/