I'm trying to understand the concepts of Linked Lists. I've searched for information about my question but I haven't found any answer which would help me.
I'd like to know how to check if linked list is sorted?
Evidently, we can't use the simple two lines function as for regular lists.
For example if I want to check if my list is sorted(without using list.sort()
), I'll create the function like this:
def is_sorted(l):
return all(a <= b for a, b in zip(l[:-1], l[1:]))
But for the linked list, should I compare list tail and head values? How it works exactly?
Contruction I use to create Linked Lists:
class Node :
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
node = Node(data)
if self.head == None:
self.head = node
else:
node.next = self.head
node.next.prev = node
self.head = node
def search(self, k):
p = self.head
if p != None :
while p.next != None :
if ( p.data == k ) :
return p
p = p.next
if ( p.data == k ) :
return p
return None
def remove( self, p ) :
tmp = p.prev
p.prev.next = p.next
p.prev = tmp
def __str__( self ) :
s = ""
p = self.head
if p != None :
while p.next != None :
s += p.data
p = p.next
s += p.data
return s