Delete all occurrences of a given key in a linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self,val,next_node=None): | |
self.val=val | |
self.next_node = next_node | |
def remove_all_n(head,n): | |
_head = head | |
while _head and _head.val == n: | |
_head = _head.next_node | |
if _head: | |
_second = _head.next_node | |
head = _head | |
while _second: | |
if _second.val == n: | |
if _second.next_node: | |
_head.next_node = _second.next_node | |
_second = _second.next_node | |
else: | |
_head.next_node = _second.next_node | |
_second = None | |
else: | |
_head = _second | |
_second = _second.next_node | |
return head | |
head=Node(3,Node(3,Node(3,Node(1,Node(3,Node(3,Node(3,Node(3,Node(3))))))))) | |
head = remove_all_n(None,3) | |
while head.next_node: | |
print (head.val) | |
head = head.next_node | |
Comments
Post a Comment