'Making a function to clone a linked list without using the copy function
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
# find a node which contains the data matching the input value
def findNode(self, value):
curr = self.head
while curr:
if curr.data == value:
return curr
curr = curr.next
return curr
# add a new node as the first node
def addNode(self, data):
newNode = Node(data) # create the new node
newNode.next = self.head
self.head = newNode
self.size+=1
# print the data in all the nodes
def printNode(self):
listprint = []
curr = self.head
while curr:
listprint.append(curr.data)
curr = curr.next
print(listprint)
#what i am trying to make
def duplicateLL(original):
newlist = LinkedList()
curr = original
if not curr:
return
while curr != None:
newlist.addNode(curr)
curr = curr.next
return newlist
#to test if function works
LLA = LinkedList()
for n in range(1,5):
LLA.addNode(n)
LLB = duplicateLL(LLA)
# modify LLA
curr = LLA.head
for n in range(LLA.size):
curr.data += 10
curr = curr.next
LLA.printNode()
LLB.printNode()
# driver code will be executed if this file is executed directly
# driver code will not be executed if this file is imported into another file
if __name__ == "__main__":
mylinkedlist = LinkedList()
for i in range(5):
mylinkedlist.addNode(2*i)
mylinkedlist.printNode()
I am trying to make a function duplicateLL, which is outside of the linked list class. Function duplicateLL is supposed to clone a linked list without using the built in copy function.
**** Note that I can only edit the function duplicateLL.***
The code prompts out: 'LinkedList' object has no attribute 'next'.
What am I doing wrong?
The outputs should be:
[14, 13, 12, 11]
[4, 3, 2, 1]
[8, 6, 4, 2, 0]
Solution 1:[1]
There was two problem for the duplicateLL function.
First, you tried to search through LinkedList which has no next attribute. Therefore, you need to use Node to travel through each element, so I assigned Node attribute to curr variable in duplicateLL function.
Second, you need to add the data of the node with the addNode function. I changed that part as well.
Here is the code:
def duplicateLL(original : LinkedList):
newlist = LinkedList()
curr = original.head
if not curr:
return
while curr != None:
newlist.addNode(curr.data)
curr = curr.next
return newlist.reverse()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
