I wanted to solve the palindrome linked list problem.
I went through the linked list, but I don't know how to refer to it in a different function. Here's my code (not working):
def __init__ (self):
self.head = None
def add_end(self, data):
newNode = Node(data)
n = self.head
if self.head is None:
self.head= newNode
n = self.head
while n:
n = n.ref
return self.head
def palindrom(self):
fast = self.head
slow = self.head
while fast and fast.ref:
fast = fast.next.ref
slow = slow.ref
#reserve second half
prev = None
while slow:
tmp = slow.ref
slow.ref = prev
prev =slow
slow = tmp
Could you please help me solve the problem?
Related
This is part of my doubly linked list deque python code.
The 'appendleft' function written almost similar to the 'append' function is normally output. Why is the last 'append('apple')' code not output normally in the 'Group_of_append' function?
class Node:
def __init__(self,item,prev,next):
self.item = item
self.prev = prev
self.next = next
class deque:
def __init__(self,name):
self.name = name
self.head = Node(None,None,None)
self.tail = Node(None,self.head,None)
self.head.next = self.tail
self.size = 0
def append(self,item):
current = self.head
new_node = Node(item,None,None)
while current.next != None:
current = current.next
current.next = new_node
new_node.prev = current
self.tail = new_node
self.size += 1
return
def appendleft(self,item):
current = self.tail
new_node = Node(item,None,None)
while current.prev != None:
current = current.prev
current.prev = new_node
new_node.next = current
self.head = new_node
self.size += 1
return
def print_list(self):
p = self.head
while p.next != None:
if p.item == None:
pass
else:
print(p.item,end=' ')
p = p.next
def Group_of_append(self):
print('Group_of_append')
self.append('graphe')
self.append('cherry')
self.append('apple')
self.appendleft('watermelon')
self.appendleft('strawberry')
self.print_list()
print(" ")
deq = deque('name')
deq.Group_of_append()
the result is
strawberry watermelon graphe cherry
The last append code on Group_of_append, self.append('apple') have no effect.
While defining the 'append' function, I thought that there would be no output due to one more size being insufficient.
So, I changed 'append' function on deque like this
def append(self,item):
self.size += 1
current = self.head
new_node = Node(item,None,None)
while current.next != None:
current = current.next
current.next = new_node
new_node.prev = current
self.tail = new_node
self.size += 1
return
But the result was same(still the lastest 'append' function doesn't print anything)
strawberry watermelon graphe cherry
Your appends work fine. Problem lies in your print_list function which stops when p.next is None. Which means your last element will not be printed because its next is None.
All in all, your logic for this list is very strange and could use a lot of rework, it would make finding mistakes like this one a lot easier for you. For example, this iterating through the whole list when appending even though you have both head and tail readily available in the deque object.
I am trying to create a linkedlist with a infinite circle like this 0->1->2->3->4->5-**>2**->3->4->5-**>2**->3->4->5-> ........., below is my code:
class node():
def __init__(self, val):
self.val = val
self.nextNode = None
def __repr__(self):
return "%s" % self.val
class linkedList():
def __init__(self):
self.head = None
def addNode(self, nodeVal):
newNode = node(nodeVal)
if self.head is None:
self.head = newNode
else:
tmp = self.head
while tmp.nextNode is not None:
tmp = tmp.nextNode
tmp.nextNode = newNode
def linkNode(self, node):
if self.head is None:
raise Exception("list can't be None")
tmp = self.head
while tmp.nextNode is not None:
tmp = tmp.nextNode
tmp.nextNode = node
def __repr__(self):
tmp = self.head
val = []
while tmp is not None:
val.append(tmp.val)
tmp = tmp.nextNode
return "vals are %s" % val
s = linkedList()
head = node(0)
node1 = node(1)
node2 = node(2)
node3 = node(3)
node4 = node(4)
node5 = node(5)
s.addNode(head)
s.addNode(node1)
s.addNode(node2)
s.addNode(node3)
s.addNode(node4)
s.addNode(node5)
s.linkNode(node2)
print(s)
But the output is this: vals are [0, 1, 2, 3, 4, 5, 2] which is not a circle.
As your method addNode expects a value, and will create a node for it, you should not call it with a node as argument.
So without altering your class methods, your main code could be as below. BTW, I find s a bad name for a list -- it is often used for a string -- so I named it lst instead:
lst = linkedList()
lst.addNode(0)
lst.addNode(1)
lst.addNode(2)
lst.addNode(3)
lst.addNode(4)
lst.addNode(5)
lst.linkNode(lst.next.next)
print(lst)
Not related, but here are some ways to improve your class:
as addNode each time needs to traverse the whole list, it might be good for your linked list to maintain a reference to the tail node. That way you can append a new node at the end in constant time.
addNode could also return the newly added node, so you can use that later for your call to linkNode
Here is how your code would look after implementing those ideas:
def __init__(self):
self.head = None
self.tail = None
def addNode(self, nodeVal):
newNode = node(nodeVal)
if self.head is None:
self.head = newNode
else:
self.tail.next = newNode
self.tail = newNode
return newNode
def linkNode(self, node):
if self.head is None:
raise Exception("list can't be None")
self.tail.next = node
# Main code
lst = linkedList()
lst.addNode(0)
lst.addNode(1)
backref = lst.addNode(2)
lst.addNode(3)
lst.addNode(4)
lst.addNode(5)
lst.linkNode(backref)
print(lst)
It is happening because in addNode you are creating a new node by doing
newNode = node(nodeVal)
which means when you later pass node2 to linkNode it is still a node with nextNode=None as create by the class Node
Just remove that line and you are good to go.
A small detail is needed, then it should work as you intend.
Replace your line s.linkNode(node2) with s.linknode(s.head.nextNode.nextNode)
Then to print the x first elements in the cycle use the following:
tmp = s.head
for i in range(x):
print(tmp.val)
tmp = tmp.nextNode
Note don't do print(s), as that will do an infinite loop in the cycle
The reason for the previous not working, is that you have in the function addNode() the following newNode = node(nodeVal) so it creates new nodes with no connection to the list.
This is my node class and Mylist class
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class MyList():
def __init__(self,head=None):
self.head = head
def showList(self):
temp = self.head
while (temp):
print(temp.data)
temp = temp.next
if self.head is None:
print("Empty List")
This is my showeven number function
def showeven(even):
head = None
while even:
if even.data % 2 == 0:
new_Node = Node(even.data, None)
if head is None:
tail = new_Node
head = new_Node
else:
tail.next = new_Node
tail = new_Node
MyList(head).showList()
Can you guys help me create a tester class or some sort of thing for this
You can simply write something like this.
def print_even_nodes(self):
traverse = self.head
while (traverse != None):
if (traverse.data % 2 == 0):
print(traverse.data)
traverse = traverse.next
It is pretty much similar to printing the whole singly linked list, the only key difference is that we check if that particular node (node.data field) is divisible by 2. If it is true we print out the element else we go to the next node.
learning how to make linked lists?
pls provide with better solution if possible.
added push ,insertafter ,printlist,append functions.
learning how to make linked lists?
pls provide with better solution if possible.
added push ,insertafter ,printlist,append functions.
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertAfter(self,prev_node,new_data):
if prev_node is None:
print('Enter valid previous node data')
return
new_node = Node(new_data)
new_node.next = prev_node.next
prev_node.next = new_data
def append(self,new_data):
new_node= Node(new_data)
if self.head is None:
self.head = new_node
last = self.head
#while last.next!= None:
#temp = last.next
#last =temp.next
while last.next:
last = last.next
last.next = new_node
def printList(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
if __name__ =='__main__':
llist = LinkedList()
llist.append(7)
llist.append(8)
llist.push(5)
llist.insertAfter(Node(5),6)
llist.printList()
The fix:
def append(self,new_data):
new_node= Node(new_data)
if self.head is None:
self.head = new_node
return # <- this is the fix
...
Without this return statement, you go to this newly added node and assign its .next to itself. With this circular reference, the next .append() gets into infinite loop
The problem is in the append method. When you append the first node, self.head is None, so you execute:
self.head = new_node
But then you continue trying to find the last node, which in this case will also end up being self.head:
last = self.head
#while last.next!= None:
#temp = last.next
#last =temp.next
while last.next:
last = last.next
As a result, when you execute this line:
last.next = new_node
You are effectively setting new_node.next = new_node, which causes the next call to append to go into an infinite loop.
Having homework with an assignment of implementing a linked list with a binary search method. Since linked lists are inherently linear, this does seem odd, however the idea is apparently to show that one is able to form the search method and connect it to the LL, essentialy just simulating binary search, since its complexity will not be better then that of linear. So far i have implemented a simple linked list, together with a working linear search method.
class Node:
def __init__(self, cargo):
self.cargo = cargo
self.next = None
def get_data(self):
return self.cargo
def get_next(self):
return self.next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add(self, cargo):
new_node = Node(cargo)
if self.head == None:
self.head = new_node
if self.tail != None:
self.tail.next = new_node
self.tail = new_node
def PrintList(self):
node = self.head
while node != None:
print(node.cargo)
node = node.next
def length(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count
def linSearch(self, cargo):
current = self.head
found = False
while current and found is False:
if current.get_data() == cargo:
found = True
else:
current = current.get_next()
return found
def binSearch(self, cargo):
LL = LinkedList
low = 0
high = LL.length(self)-1
while low <= high:
mid = (low+high)//2
if self[mid] > cargo:
high = mid-1
elif self[mid] < cargo:
low = mid+1
else:
return mid
return -1
LL = LinkedList()
LL.add(1)
LL.PrintList()
print(LL.linSearch(2))
print(LL.binSearch(1))
Current error when running the binSearch method is that object does not support indexing. Unfortunately, i’m stuck.