dequeue in circularly linked list in python The Next CEO of Stack OverflowHow do I check if a list is empty?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonDoes Python have a ternary conditional operator?How to make a flat list out of list of lists?How do I concatenate two lists in Python?How do I list all files of a directory?Does Python have a string 'contains' substring method?

Limits on contract work without pre-agreed price/contract (UK)

What's the best way to handle refactoring a big file?

Received an invoice from my ex-employer billing me for training; how to handle?

How did people program for Consoles with multiple CPUs?

If a black hole is created from light, can this black hole then move at speed of light?

Complex fractions

How to solve a differential equation with a term to a power?

Can I equip Skullclamp on a creature I am sacrificing?

What does convergence in distribution "in the Gromov–Hausdorff" sense mean?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

What happened in Rome, when the western empire "fell"?

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

Would a galaxy be visible from outside, but nearby?

If/When UK leaves the EU, can a future goverment conduct a referendum to join the EU?

How to avoid supervisors with prejudiced views?

Is micro rebar a better way to reinforce concrete than rebar?

Which tube will fit a -(700 x 25c) wheel?

Are there any limitations on attacking while grappling?

Is it ever safe to open a suspicious html file (e.g. email attachment)?

To not tell, not take, and not want

If the heap is initialized for security, then why is the stack uninitialized?

Do I need to enable Dev Hub in my PROD Org?



dequeue in circularly linked list in python



The Next CEO of Stack OverflowHow do I check if a list is empty?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonDoes Python have a ternary conditional operator?How to make a flat list out of list of lists?How do I concatenate two lists in Python?How do I list all files of a directory?Does Python have a string 'contains' substring method?










0















I am working on the implementation of Queue with a circularly linked list in python. Below is the pictorial representation of circularly LinkedList



Image for reference



I was able to implement most of the code except the dequeue routine. In dequeue routine, one has to keep track of the previous node reference as well as the next node reference with respect to current node. In double linked list, it's easy to implement. However, I have no idea how to implement this concept in single linked list.



class CircularQueue:

''' Queue implementation using a Circularly linked list for storage '''

class _Node:

__slots__ == '_element','_next'

def __init__(self,element,next):
self._element = element
self._next = next

def __init__(self):
'''Create an empty queue'''
self._current = None
self._size = 0

def __len__(self):
return self._size

def is_empty(self):
return self._size == 0

def enqueue(self,e):

node = self._Node(e,None)
if self.is_empty():
newest._next = newest
else:
curr_node = self._current._next
node._next = curr_node
self._current = node
self._size += 1

def dequeue(self):
if self.is_empty():
raise Empty('Stack is empty')


It would be more helpful if anyone can give me thoughts on how to move forward in dequeue routine.










share|improve this question






















  • Circular queues were invented to deal with fixed arrays; there is no reason to make a linked list implementation circular.

    – meowgoesthedog
    Mar 7 at 15:30















0















I am working on the implementation of Queue with a circularly linked list in python. Below is the pictorial representation of circularly LinkedList



Image for reference



I was able to implement most of the code except the dequeue routine. In dequeue routine, one has to keep track of the previous node reference as well as the next node reference with respect to current node. In double linked list, it's easy to implement. However, I have no idea how to implement this concept in single linked list.



class CircularQueue:

''' Queue implementation using a Circularly linked list for storage '''

class _Node:

__slots__ == '_element','_next'

def __init__(self,element,next):
self._element = element
self._next = next

def __init__(self):
'''Create an empty queue'''
self._current = None
self._size = 0

def __len__(self):
return self._size

def is_empty(self):
return self._size == 0

def enqueue(self,e):

node = self._Node(e,None)
if self.is_empty():
newest._next = newest
else:
curr_node = self._current._next
node._next = curr_node
self._current = node
self._size += 1

def dequeue(self):
if self.is_empty():
raise Empty('Stack is empty')


It would be more helpful if anyone can give me thoughts on how to move forward in dequeue routine.










share|improve this question






















  • Circular queues were invented to deal with fixed arrays; there is no reason to make a linked list implementation circular.

    – meowgoesthedog
    Mar 7 at 15:30













0












0








0








I am working on the implementation of Queue with a circularly linked list in python. Below is the pictorial representation of circularly LinkedList



Image for reference



I was able to implement most of the code except the dequeue routine. In dequeue routine, one has to keep track of the previous node reference as well as the next node reference with respect to current node. In double linked list, it's easy to implement. However, I have no idea how to implement this concept in single linked list.



class CircularQueue:

''' Queue implementation using a Circularly linked list for storage '''

class _Node:

__slots__ == '_element','_next'

def __init__(self,element,next):
self._element = element
self._next = next

def __init__(self):
'''Create an empty queue'''
self._current = None
self._size = 0

def __len__(self):
return self._size

def is_empty(self):
return self._size == 0

def enqueue(self,e):

node = self._Node(e,None)
if self.is_empty():
newest._next = newest
else:
curr_node = self._current._next
node._next = curr_node
self._current = node
self._size += 1

def dequeue(self):
if self.is_empty():
raise Empty('Stack is empty')


It would be more helpful if anyone can give me thoughts on how to move forward in dequeue routine.










share|improve this question














I am working on the implementation of Queue with a circularly linked list in python. Below is the pictorial representation of circularly LinkedList



Image for reference



I was able to implement most of the code except the dequeue routine. In dequeue routine, one has to keep track of the previous node reference as well as the next node reference with respect to current node. In double linked list, it's easy to implement. However, I have no idea how to implement this concept in single linked list.



class CircularQueue:

''' Queue implementation using a Circularly linked list for storage '''

class _Node:

__slots__ == '_element','_next'

def __init__(self,element,next):
self._element = element
self._next = next

def __init__(self):
'''Create an empty queue'''
self._current = None
self._size = 0

def __len__(self):
return self._size

def is_empty(self):
return self._size == 0

def enqueue(self,e):

node = self._Node(e,None)
if self.is_empty():
newest._next = newest
else:
curr_node = self._current._next
node._next = curr_node
self._current = node
self._size += 1

def dequeue(self):
if self.is_empty():
raise Empty('Stack is empty')


It would be more helpful if anyone can give me thoughts on how to move forward in dequeue routine.







python linked-list queue






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 15:25









s326280s326280

1269




1269












  • Circular queues were invented to deal with fixed arrays; there is no reason to make a linked list implementation circular.

    – meowgoesthedog
    Mar 7 at 15:30

















  • Circular queues were invented to deal with fixed arrays; there is no reason to make a linked list implementation circular.

    – meowgoesthedog
    Mar 7 at 15:30
















Circular queues were invented to deal with fixed arrays; there is no reason to make a linked list implementation circular.

– meowgoesthedog
Mar 7 at 15:30





Circular queues were invented to deal with fixed arrays; there is no reason to make a linked list implementation circular.

– meowgoesthedog
Mar 7 at 15:30












1 Answer
1






active

oldest

votes


















0














Since your linked list is unidirectional, an element does only have a reference to it's successor, but never to it's predecessor, which you would need both in order to easily close the hole in the list once you dequeue an element.



I see two possibilities: You could either make the linked list bidirectional, therefore adding a reference to the previous element. I cleaned up your implementation a bit, I hope you still can make something of this:



""" Queue implementation using a Circularly linked list for storage """


class _Node:
def __init__(self, element, next=None, previous=None):
self.element = element
if next is None:
next = self
self.next = next
if previous is None:
previous = self
self.previous = previous


class CircularQueue:
def __init__(self):
self._current = None
self._size = 0

def __len__(self):
return self._size

def get_head(self):
return self._current.element

def is_empty(self):
return self._size == 0

def next(self):
self._current = self._current.next
return self._current.element

def previous(self):
self._current = self._current.pevious
return self._current

def enqueue(self, element):
""" Adds an element at the current position, ahead of the current element """
if self.is_empty():
new_node = _Node(element)
else:
new_node = _Node(element, self._current.next, self._current)
self._current.next = new_node
self._current = new_node
self._size += 1


We can now check if our code is correct:



cq = CircularQueue()
cq.enqueue("A")
cq.enqueue("B")
cq.enqueue("C")

print(cq.get_head())
print(cq.next())
print(cq.next())
print(cq.next())


And you will see C, A, B and C printed in succession.



A bilateral queue enables us to implement a dequeue method like this:



def dequeue(self, element_key=None):
if self.is_empty():
raise KeyError('Stack is empty')

if element_key is None:
self._current.next.previous = self._current.previous
self._current.previous.next = self._current.next
return self.next()
else:
current = self._current
while self._current.element != element_key:
self.next()
if self._current == current:
raise KeyError('Element not found')
self.dequeue()


And if we test it...



print("dequeuing 'B'")
cq.dequeue("B")
print(cq.get_head())
print(cq.next())
print(cq.next())
print(cq.next())


... we should see that "dequeuing 'B'" and C, A, C & again A are printed, which makes us happy. :)



Using a unilateral approach is possible too; you might end up having less work handling references while you would have run through your entire circle (in the worst case). First, you'd skip to the next element in the queue until the next element of the current one's is the one you want to dequeue, then set the current's elements next reference to the dequeued one's next, and you are basically done.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55047306%2fdequeue-in-circularly-linked-list-in-python%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Since your linked list is unidirectional, an element does only have a reference to it's successor, but never to it's predecessor, which you would need both in order to easily close the hole in the list once you dequeue an element.



    I see two possibilities: You could either make the linked list bidirectional, therefore adding a reference to the previous element. I cleaned up your implementation a bit, I hope you still can make something of this:



    """ Queue implementation using a Circularly linked list for storage """


    class _Node:
    def __init__(self, element, next=None, previous=None):
    self.element = element
    if next is None:
    next = self
    self.next = next
    if previous is None:
    previous = self
    self.previous = previous


    class CircularQueue:
    def __init__(self):
    self._current = None
    self._size = 0

    def __len__(self):
    return self._size

    def get_head(self):
    return self._current.element

    def is_empty(self):
    return self._size == 0

    def next(self):
    self._current = self._current.next
    return self._current.element

    def previous(self):
    self._current = self._current.pevious
    return self._current

    def enqueue(self, element):
    """ Adds an element at the current position, ahead of the current element """
    if self.is_empty():
    new_node = _Node(element)
    else:
    new_node = _Node(element, self._current.next, self._current)
    self._current.next = new_node
    self._current = new_node
    self._size += 1


    We can now check if our code is correct:



    cq = CircularQueue()
    cq.enqueue("A")
    cq.enqueue("B")
    cq.enqueue("C")

    print(cq.get_head())
    print(cq.next())
    print(cq.next())
    print(cq.next())


    And you will see C, A, B and C printed in succession.



    A bilateral queue enables us to implement a dequeue method like this:



    def dequeue(self, element_key=None):
    if self.is_empty():
    raise KeyError('Stack is empty')

    if element_key is None:
    self._current.next.previous = self._current.previous
    self._current.previous.next = self._current.next
    return self.next()
    else:
    current = self._current
    while self._current.element != element_key:
    self.next()
    if self._current == current:
    raise KeyError('Element not found')
    self.dequeue()


    And if we test it...



    print("dequeuing 'B'")
    cq.dequeue("B")
    print(cq.get_head())
    print(cq.next())
    print(cq.next())
    print(cq.next())


    ... we should see that "dequeuing 'B'" and C, A, C & again A are printed, which makes us happy. :)



    Using a unilateral approach is possible too; you might end up having less work handling references while you would have run through your entire circle (in the worst case). First, you'd skip to the next element in the queue until the next element of the current one's is the one you want to dequeue, then set the current's elements next reference to the dequeued one's next, and you are basically done.






    share|improve this answer



























      0














      Since your linked list is unidirectional, an element does only have a reference to it's successor, but never to it's predecessor, which you would need both in order to easily close the hole in the list once you dequeue an element.



      I see two possibilities: You could either make the linked list bidirectional, therefore adding a reference to the previous element. I cleaned up your implementation a bit, I hope you still can make something of this:



      """ Queue implementation using a Circularly linked list for storage """


      class _Node:
      def __init__(self, element, next=None, previous=None):
      self.element = element
      if next is None:
      next = self
      self.next = next
      if previous is None:
      previous = self
      self.previous = previous


      class CircularQueue:
      def __init__(self):
      self._current = None
      self._size = 0

      def __len__(self):
      return self._size

      def get_head(self):
      return self._current.element

      def is_empty(self):
      return self._size == 0

      def next(self):
      self._current = self._current.next
      return self._current.element

      def previous(self):
      self._current = self._current.pevious
      return self._current

      def enqueue(self, element):
      """ Adds an element at the current position, ahead of the current element """
      if self.is_empty():
      new_node = _Node(element)
      else:
      new_node = _Node(element, self._current.next, self._current)
      self._current.next = new_node
      self._current = new_node
      self._size += 1


      We can now check if our code is correct:



      cq = CircularQueue()
      cq.enqueue("A")
      cq.enqueue("B")
      cq.enqueue("C")

      print(cq.get_head())
      print(cq.next())
      print(cq.next())
      print(cq.next())


      And you will see C, A, B and C printed in succession.



      A bilateral queue enables us to implement a dequeue method like this:



      def dequeue(self, element_key=None):
      if self.is_empty():
      raise KeyError('Stack is empty')

      if element_key is None:
      self._current.next.previous = self._current.previous
      self._current.previous.next = self._current.next
      return self.next()
      else:
      current = self._current
      while self._current.element != element_key:
      self.next()
      if self._current == current:
      raise KeyError('Element not found')
      self.dequeue()


      And if we test it...



      print("dequeuing 'B'")
      cq.dequeue("B")
      print(cq.get_head())
      print(cq.next())
      print(cq.next())
      print(cq.next())


      ... we should see that "dequeuing 'B'" and C, A, C & again A are printed, which makes us happy. :)



      Using a unilateral approach is possible too; you might end up having less work handling references while you would have run through your entire circle (in the worst case). First, you'd skip to the next element in the queue until the next element of the current one's is the one you want to dequeue, then set the current's elements next reference to the dequeued one's next, and you are basically done.






      share|improve this answer

























        0












        0








        0







        Since your linked list is unidirectional, an element does only have a reference to it's successor, but never to it's predecessor, which you would need both in order to easily close the hole in the list once you dequeue an element.



        I see two possibilities: You could either make the linked list bidirectional, therefore adding a reference to the previous element. I cleaned up your implementation a bit, I hope you still can make something of this:



        """ Queue implementation using a Circularly linked list for storage """


        class _Node:
        def __init__(self, element, next=None, previous=None):
        self.element = element
        if next is None:
        next = self
        self.next = next
        if previous is None:
        previous = self
        self.previous = previous


        class CircularQueue:
        def __init__(self):
        self._current = None
        self._size = 0

        def __len__(self):
        return self._size

        def get_head(self):
        return self._current.element

        def is_empty(self):
        return self._size == 0

        def next(self):
        self._current = self._current.next
        return self._current.element

        def previous(self):
        self._current = self._current.pevious
        return self._current

        def enqueue(self, element):
        """ Adds an element at the current position, ahead of the current element """
        if self.is_empty():
        new_node = _Node(element)
        else:
        new_node = _Node(element, self._current.next, self._current)
        self._current.next = new_node
        self._current = new_node
        self._size += 1


        We can now check if our code is correct:



        cq = CircularQueue()
        cq.enqueue("A")
        cq.enqueue("B")
        cq.enqueue("C")

        print(cq.get_head())
        print(cq.next())
        print(cq.next())
        print(cq.next())


        And you will see C, A, B and C printed in succession.



        A bilateral queue enables us to implement a dequeue method like this:



        def dequeue(self, element_key=None):
        if self.is_empty():
        raise KeyError('Stack is empty')

        if element_key is None:
        self._current.next.previous = self._current.previous
        self._current.previous.next = self._current.next
        return self.next()
        else:
        current = self._current
        while self._current.element != element_key:
        self.next()
        if self._current == current:
        raise KeyError('Element not found')
        self.dequeue()


        And if we test it...



        print("dequeuing 'B'")
        cq.dequeue("B")
        print(cq.get_head())
        print(cq.next())
        print(cq.next())
        print(cq.next())


        ... we should see that "dequeuing 'B'" and C, A, C & again A are printed, which makes us happy. :)



        Using a unilateral approach is possible too; you might end up having less work handling references while you would have run through your entire circle (in the worst case). First, you'd skip to the next element in the queue until the next element of the current one's is the one you want to dequeue, then set the current's elements next reference to the dequeued one's next, and you are basically done.






        share|improve this answer













        Since your linked list is unidirectional, an element does only have a reference to it's successor, but never to it's predecessor, which you would need both in order to easily close the hole in the list once you dequeue an element.



        I see two possibilities: You could either make the linked list bidirectional, therefore adding a reference to the previous element. I cleaned up your implementation a bit, I hope you still can make something of this:



        """ Queue implementation using a Circularly linked list for storage """


        class _Node:
        def __init__(self, element, next=None, previous=None):
        self.element = element
        if next is None:
        next = self
        self.next = next
        if previous is None:
        previous = self
        self.previous = previous


        class CircularQueue:
        def __init__(self):
        self._current = None
        self._size = 0

        def __len__(self):
        return self._size

        def get_head(self):
        return self._current.element

        def is_empty(self):
        return self._size == 0

        def next(self):
        self._current = self._current.next
        return self._current.element

        def previous(self):
        self._current = self._current.pevious
        return self._current

        def enqueue(self, element):
        """ Adds an element at the current position, ahead of the current element """
        if self.is_empty():
        new_node = _Node(element)
        else:
        new_node = _Node(element, self._current.next, self._current)
        self._current.next = new_node
        self._current = new_node
        self._size += 1


        We can now check if our code is correct:



        cq = CircularQueue()
        cq.enqueue("A")
        cq.enqueue("B")
        cq.enqueue("C")

        print(cq.get_head())
        print(cq.next())
        print(cq.next())
        print(cq.next())


        And you will see C, A, B and C printed in succession.



        A bilateral queue enables us to implement a dequeue method like this:



        def dequeue(self, element_key=None):
        if self.is_empty():
        raise KeyError('Stack is empty')

        if element_key is None:
        self._current.next.previous = self._current.previous
        self._current.previous.next = self._current.next
        return self.next()
        else:
        current = self._current
        while self._current.element != element_key:
        self.next()
        if self._current == current:
        raise KeyError('Element not found')
        self.dequeue()


        And if we test it...



        print("dequeuing 'B'")
        cq.dequeue("B")
        print(cq.get_head())
        print(cq.next())
        print(cq.next())
        print(cq.next())


        ... we should see that "dequeuing 'B'" and C, A, C & again A are printed, which makes us happy. :)



        Using a unilateral approach is possible too; you might end up having less work handling references while you would have run through your entire circle (in the worst case). First, you'd skip to the next element in the queue until the next element of the current one's is the one you want to dequeue, then set the current's elements next reference to the dequeued one's next, and you are basically done.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 7 at 16:58









        AarkonAarkon

        358




        358





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55047306%2fdequeue-in-circularly-linked-list-in-python%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко