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

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved