In: Computer Science
a python function that reads two text files and merges in to one Linked List, be able to print each Item in the new single Linked List
class Node(object):
item = -1
next = None
def __init__(self, item, next):
self.item = item
self.next = next
================================
textfile!
979
2744
5409
1364
4948
4994
5089
703
1994
4637
2228
4004
1088
2812
170
5179
2614
238
4523
4849
3592
3258
1951
3440
3977
1247
4076
1824
4759
4855
5430
347
974
5180
5159
3074
4462
3600
5824
1490
1941
4744
855
4940
1442
792
609
254
2203
2343
2550
1955
5513
4725
2935
4024
4979
5765
625
2888
924
5989
4119
1572
176
2773
3800
200
3389
4245
3849
3170
4773
2344
1413
292
2603
4694
5579
4012
5584
5352
3293
5516
1008
5395
545
3340
4967
2050
870
2462
2606
4850
4731
450
4052
1279
2506
3937
396
222
3928
2557
3070
444
2599
3462
2418
1180
3290
2046
493
2708
3650
973
57
1846
3300
265
3572
3543
4439
1807
========
textfile2
4964
157
2374
3617
2833
2413
388
3642
3468
3331
2537
1830
4923
1718
class Node(object):
data = -1
next_node = None
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
#define a different class for linkedlist
class LinkedList(object):
def __init__(self, head=None):
self.head = head
#function to insert
def insert(self, data):
new_node = Node(data)
new_node.set_next(self.head)
self.head = new_node
#function to print the elements of the linked list
def print_nodes(self):
current=self.head
while current:
print(current.get_data())
current=current.get_next()
file1=open("textfile!.txt","r")
file2=open("textfile2.txt","r")
ll=LinkedList()
for i in file1:
ll.insert(i)
for i in file2:
ll.insert(i)
file1.close()
file2.close()
ll.print_nodes()
# prints data in reverse fashion
sample output:
1718
4923
1830
2537
3331
3468
3642
388
2413
2833
3617
2374
157
4964
1807
4439
3543
3572
265
3300
1846
57
973
3650
2708
493
2046
3290
1180
2418
3462
2599
444
3070
2557
3928
222
396
3937
2506
1279
4052
450
4731
4850
2606
2462
870
2050
4967
3340
545
5395
1008
5516
3293
5352
5584
4012
5579
4694
2603
292
1413
2344
4773
3170
3849
4245
3389
200
3800
2773
176
1572
4119
5989
924
2888
625
5765
4979
4024
2935
4725
5513
1955
2550
2343
2203
254
609
792
1442
4940
855
4744
1941
1490
5824
3600
4462
3074
5159
5180
974
347
5430
4855
4759
1824
4076
1247
3977
3440
1951
3258
3592
4849
4523
238
2614
5179
170
2812
1088
4004
2228
4637
1994
703
5089
4994
4948
1364
5409
2744
979