Snippets
Created by
aslan ali
last modified
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | class LinkedList(object):
def __init__(self, value=None):
if value is None:
self.root = None
def iterate_list(self):
if self.root is None:
print("No node created yet")
return
else:
print("Inside else of iterate_list")
a = self.root
while a:
print(a, a.data)
a = a.next
# print("value of last a ",a)
def find(self, value):
if self.root is None:
print("No node created yet")
return
else:
print("Inside else of find")
a = self.root
prev_a = a
while a:
if a.data == value:
print("I found", a.data)
return a, prev_a
print(a, a.data)
prev_a = a
a = a.next
print("value not found ", a )
def recurse_list(self):
print("inside recusrion")
def reverse_list(self):
print("Inside reverse_list")
if not self.root:
print("Empty linked LinkedList")
return
first_node = self.root
if not first_node.next:
print("only one node ", first_node.data)
return
print( "beyond" )
next_node = first_node.next
first_node.next = None
while next_node.next is not None:
print("inside while")
temp = first_node
first_node, next_node = next_node, next_node.next
first_node.next = temp
self.root = next_node
self.root.next = first_node
print("This is head of list", self.root.data)
def add_node_end(self, data):
if self.root is None:
print("No node created yet")
self.root = Node(data, next=None)
return
else:
print("Inside else of add_node_end")
first_node = self.root
last_node = first_node
while first_node:
last_node = first_node
first_node = first_node.next
print("last node data is", last_node.data)
last_node.next = Node(data)
return
def add_node(self, data, next=None):
if self.root is None:
self.root = Node(data, next)
def add_node_beg(self, data, next=None):
if self.root is None:
self.root = Node(data, next)
else:
older_node = self.root
new_node = Node(data, older_node)
self.root = new_node
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
print(type(self.next))
def getvalue(self, existing_node):
print("Inside of getvalue")
print(existing_node.data)
return
l = LinkedList()
#l.add_node(12)
l.add_node_beg(13)
l.add_node_beg(1323)
l.add_node_beg(133)
l.add_node_beg(13212)
l.add_node_beg(1)
l.add_node_end(11)
l.add_node_beg(123)
l.add_node_end(112)
l.iterate_list()
l.reverse_list()
l.iterate_list()
l.recurse_list()
#found_at,found_before=l.find(11)
#print("This is found",found_at.data,found_before.data)
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.