简体   繁体   中英

removing an element from a linked list in python

I was wondering if any of you could give me a walk through on how to remove an element from a linked list in python, I'm not asking for code but just kinda a pseudo algorithm in english. for example I have the linked list of 1 -> 2 -> 2 -> 3 -> 4 and I want to remove one of the 2's how would i do that? I thought of traversing through the linked list, checking to see if the data of one of the nodes is equal to the data of the node after it, if it is remove it. But I'm having trouble on the removing part. Thanks!

Instead of deleting the element, all you need to do is change the pointer . For example, you want the previous element of the node you want to delete to point to the element after the element you want to delete:

node is what you want to delete

node.parent.next = node.next

You need to maintain two pointers

  1. One is to check whether the current node's data is same as the value to be deleted
  2. The other pointer is to keep the reference of the previous node to the current node. This is required because when you delete the current node, the current node's next one needs to be pointed to the current node's previous one.

Here is the code to do the same in python:

def remove(self, val):
    if self.head == val:
        self.head = self.head.next
        return

    tmp = self.head.next
    tmp_prev = self.head

    while tmp.next is not None:
        if tmp.data == val:
             tmp_prev.next = tmp.next
        tmp = tmp.next
        tmp_prev = tmp.next

    return

You don't need to "delete" the node, just "skip" it. That is, change Node1's next member to the second Node2.

Edit your question if you would like specific code examples (which are the norm for this site).

You can do something like:

if element.next.value == element.value: element.next = element.next.next

Just be carefull to free the memory if you are programing this in C/C++ or other language that does not have GC

如果你想在两端实现快速追加和弹出的类似列表的容器,我强烈推荐容器库中的 deque 模块https://docs.python.org/2/library/collections.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM