-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.py
54 lines (47 loc) · 1.26 KB
/
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
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self, elements=None):
self.head = None
if elements is not None:
for element in elements:
self.insert(element)
def insert(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def reverse(self):
prev = None
current = self.head
while current:
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
def __str__(self):
result = []
current = self.head
while current:
result.append(current.data)
current = current.next
return ' -> '.join(map(str, result))
def __add__(self, other):
result = LinkedList()
current = other.head
while current:
result.insert(current.data)
current = current.next
current = self.head
while current:
result.insert(current.data)
current = current.next
return result
l1 = LinkedList([1, 2, 3])
l2 = LinkedList([4, 5, 6])
print(l1)
print(l2)
l3 = l1 + l2
print(l3)