In: Computer Science
concatenate(lst1, lst2 )
Given two (possibly empty) unordered lists, concatenate them such that the first list comes first.Example: When the first input unordered list lst1 is [1, 2, 3] and the second lst2 is [7,8,9], the outputunordered list is [1,2,3,7,8,9].
Use codes:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, data):
self.data = data
def setNext(self, node):
self.next = node
class UnorderedList:
def __init__(self):
self.head = None
def add(self, data):
newNode = Node(data)
newNode.setNext(self.head)
self.head = newNode
def length(self):
cur = self.head
count = 0
while cur:
cur = cur.getNext()
count += 1
return count
def isEmpty(self):
return self.head == None
def search(self, data):
cur = self.head
while cur:
if cur.getData() == data:
return True
cur = cur.getNext()
return False
def remove(self, data):
if self.head.getData() == data:
self.head = self.head.getNext()
else:
cur = self.head
while cur.getNext() and cur.getNext().getData() != data:
cur = cur.getNext()
if cur.getNext():
cur.setNext(cur.getNext().getNext())
class Node:
def __init__(self, data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, data):
self.data = data
def setNext(self, node):
self.next = node
class UnorderedList:
def __init__(self):
self.head = None
def add(self, data):
newNode =
Node(data)
newNode.setNext(self.head)
self.head = newNode
def length(self):
cur = self.head
count = 0
while cur:
cur = cur.getNext()
count += 1
return count
def isEmpty(self):
return self.head ==
None
def search(self, data):
cur = self.head
while cur:
if cur.getData() == data:
return True
cur = cur.getNext()
return False
def remove(self, data):
if self.head.getData()
== data:
self.head = self.head.getNext()
else:
cur = self.head
while cur.getNext() and cur.getNext().getData() != data:
cur = cur.getNext()
if cur.getNext():
cur.setNext(cur.getNext().getNext())
def display(self):
curr = self.head
while curr !=
None:
print(curr.getData(), end = " ")
curr = curr.getNext()
print()
def concatenate(lst1, lst2):
first = lst1.head
second = lst2.head
if first == None:
lst1.head =
lst2.head
while first.getNext() != None:
first =
first.getNext()
first.setNext(lst2.head)
lst1 = UnorderedList()
lst1.add(3)
lst1.add(2)
lst1.add(1)
lst2 = UnorderedList()
lst2.add(9)
lst2.add(8)
lst2.add(7)
concatenate(lst1, lst2)
lst1.display()