【问题标题】:Memory Editing in Python. Delete Last Node in LinkedListPython中的内存编辑。删除 LinkedList 中的最后一个节点
【发布时间】:2018-04-18 19:29:37
【问题描述】:

来自破解编码面试。任务 2.3。

你有一个链表,你需要创建一个函数,只接受该列表中的节点并将其从该列表中删除。

当节点在中间时,很简单。您只需将字段 valuenext 重新分配给列表中的下一个节点。但是如何去掉列表中的最后一个节点呢?

我一直在寻找一种在 Python 中修改内存的方法,但找不到任何真正有效的方法。有人可以提出任何建议吗?

代码如下:

class LinkedListNode:
    def __init__(self, item, next = None):
        self.item = item
        self.next = next


class LinkedList:
    def __init__(self):
        self.__head = None

    def append(self, item):
        self.__head = LinkedListNode(item, self.__head)

    @property
    def head(self):
        return self.__head

def remove_node(node):
    if node.next:
        next = node.next
        node.item = next.item
        node.next = next.next
        next.next = None
    else:
        # WHAT TO DO HERE?
        pass

【问题讨论】:

  • 如果 node.next.next 是 None 那么 node.next = None,不是那么简单吗?
  • 你确定你应该为你的链表类写一个函数,而不是一个方法吗?你确定你的链表应该是单链的吗?
  • node.next 已经是 None,因为它是列表中的最后一个节点。是的,函数,因为你只有一个节点,而不是整个列表,这是我的问题。想象一种情况,您只收到列表的最后一个节点。在 C++ 中,您通过内存地址修改值。如何在 Python 中做同样的事情?
  • remove_node 没有删除节点;它正在删除给定节点 after 的节点。如果没有这样的节点,则无事可做;你可以回来。
  • 你也不能在 C++ 中做到这一点。

标签: python python-3.x memory-management


【解决方案1】:

在玩弄了 C++ 实现之后,我意识到了以下几点。

想象一下,你有 3 个元素的列表:3 -> 2 -> 1。

我们要删除包含值1 的最后一个节点。如果我们使用 C++ 代码并检查我们的元素发生了什么,我们将看到存储在节点 321 中的内容:

3: 48416413-411270030000000
2: 32416413-411270020000000
1: 0000000010000000

我们可以看到每个节点都有一个next指针和一个data值。最后一个节点有一个next 指针。所以,为了做我想做的事,我们需要先到最后一个节点,并将它的指针设置为 0x0(空指针)。这意味着在 C++ 或 Python 当前实现上都是不可能的,除非有办法找到指向内存槽的指针。

请参阅下面的 C++ 实现。

#include <iostream>
#include <string>
using namespace std;

class Node
{
    public:
    Node* next;
    int data;
};

class List
{
    private:
    Node *head;

    public:
    List()
    {
        head = NULL;
    }

    Node* get_head() { return head; }

    void append(int val) {
        Node* newHead = new Node();
        newHead->data = val;
        newHead->next = head;
        head = newHead;
    }
}

int main() {
    List* list = new List();
    list->append(1);
    list->append(2);
    list->append(3);

    cout << "List: " << list->str() << "\n";

    Node* node = list->get_head();
    while (node) {
        cout << node->data << ": ";
        string str(reinterpret_cast<char*>(node), sizeof(*node));
        for(string::iterator it = str.begin(); it != str.end(); ++it) {
            int i = *it;
            cout << i;
        }
        cout << "\n";

        node = node->next;
    }

    cout << "List: " << list->str() << "\n";

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 2015-08-26
    相关资源
    最近更新 更多