-
Notifications
You must be signed in to change notification settings - Fork 0
/
doubly_linked_list.py
86 lines (68 loc) · 2.06 KB
/
doubly_linked_list.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
86
from node import Node
class DoublyLinkedList:
def __init__(self):
self.head = None
def push(self, data):
self.head = Node(data, self.head)
def push(self, data):
if not self.head:
self.head = Node(data, self.head)
return
new_node = Node(data, self.head)
self.head.prev_node = new_node
self.head = new_node
def reverse(self):
temp = self.head
while temp.next_node:
temp = temp.next_node
self.head = temp
while temp:
swap = temp
temp.next_node = temp.prev_node
temp.prev_node = swap.next_node
temp = temp.next_node
def insert_at_index(self, index: int, data):
temp = self.head
if not index:
self.push(data)
return
i = 0
while index > i:
temp = temp.next_node
i += 1
new_node = Node(data, prev_node=temp.prev_node, next_node=temp)
temp.prev_node.next_node = new_node
temp.prev_node = new_node
def delete_node(self, index: int):
temp = self.head
if not index:
self.head = temp.next_node
return
i = 0
while index > i:
temp = temp.next_node
i += 1
prev_node = temp.prev_node
next_node = temp.next_node
prev_node.next_node = next_node
if not next_node:
return
next_node.prev_node = prev_node
def append(self, data):
temp = self.head
while temp.next_node:
temp = temp.next_node
temp.next_node = Node(data, prev_node=temp)
def print_list(self, backwards=False):
temp = self.head
print('Travelsal fowards')
while temp.next_node:
print(temp.val, end=" ")
temp = temp.next_node
print(temp.val)
if backwards:
print('Travelsal backwards')
while temp:
print(temp.val, end=" ")
temp = temp.prev_node
print()