-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitem-1.py
70 lines (63 loc) · 1.75 KB
/
item-1.py
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
class Node:
def __init__(self,data):
self.next = None
self.data = data
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def __str__(self):
s = ""
cur = self.head
while cur != None:
s += str(cur.data)
cur = cur.next
if cur != None:
s += "->"
return s
def isEmpty(self):
return self.size == 0
def append(self, data):
newNode = Node(data)
if self.isEmpty():
self.head = newNode
else:
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = newNode
self.size += 1
def insert(self, index, data):
newNode = Node(data)
if self.isEmpty():
self.head = newNode
elif index == 0:
newNode.next = self.head
self.head = newNode
else:
cur = self.head
cur_idx = 0
while cur_idx < index-1:
cur_idx+=1
cur = cur.next
newNode = cur.next
cur.next = newNode
self.size += 1
def remove(self,index):
if not self.isEmpty():
if index == 0:
cur = self.head
if cur.next!=None:
cur = cur.next
self.head.next = None
self.head = cur
else:
cur_idx = 0
cur = self.head
while cur_idx != index-1:
cur = cur.next
cur_idx += 1
curNext = cur.next
cur.next = curNext.next
curNext.next = None
self.size -= 1