-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathData Structures.py
85 lines (71 loc) · 1.97 KB
/
Data Structures.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class MyList:
def __init__(self):
self.List = []
def push(self, num):
self.List = self.List +[num]
def pop(self):
if self.List:
temp = self.List[-1]
self.List = self.List[0:len(self.List)-1]
return temp
else:
return -1
def print(self):
print(self.List)
import heapq
class MyHeap:
def __init__(self,arr=[]):
self.heapfy(arr)
def heapfy(self,arr):
self.arr = arr
total = len(self.arr)
for idx,num in enumerate(self.arr):
left,right = 2*idx+1,2*idx+2
if left < total and self.arr[idx] > self.arr[left]:
self.arr[idx],self.arr[left] = self.arr[left], self.arr[idx]
if right < total and self.arr[idx] > self.arr[right]:
self.arr[idx],self.arr[right] = self.arr[right],self.arr[idx]
def heappush(self,a):
self.arr.append(a)
now = len(self.arr)-1
next = (now-1)//2
while self.arr[now] < self.arr[next]:
if now == 0:
break
self.arr[now],self.arr[next] = self.arr[next],self.arr[now]
now = next
next = (now-1)//2
print(self.arr)
class Node:
def __init__(self,data):
self.data = data
self.next = None
def add(self,node):
if self.next is None:
self.next = node
else:
n = self.next
while n.next is None:
n.next = node
break
else:
n = n.next
def select(self,idx):
n = self.next
for i in range(idx-1):
n = n.next
return n.data
class linkedList:
def __init__(self,data,next=None):
self.data = data
self.next = next
a = linkedList(3,linkedList(4))
print(a.next.data)
a = [4,7,1,3,10]
heapq.heapify(a)
heapq.heappush(a,1)
print(a)
heapq.heappop(a)
print(a)
heap = MyHeap([4,7,1,3,10])
heap.heappush(1)