简体   繁体   English

删除传递给链表C中的函数的单个节点

[英]Delete a single node passed to a function in a linked list C

I have a function deleteNode that receives the head of the list, and the node to be deleted. 我有一个函数deleteNode ,它接收列表的开头以及要删除的节点。 When I run this, It successfully removes the node, but it also removes everything after it. 当我运行它时,它成功删除了该节点,但它也删除了它之后的所有内容。 I believe it has to do with me rebuilding the list, but I can't figure out where my logic is wrong so I could use a little help. 我相信这与我重新构建列表有关,但是我无法弄清楚我的逻辑错在哪里,因此我可以使用一些帮助。 Here is the function code: 这是功能代码:

void deleteNode(struct lnode** head, struct lnode* node) {
    struct lnode* nextNode = nodeGetNext(node);
    printf("word: \n%s\n",nodeGetWord(nextNode));
    struct lnode* nodeToDelete = node;


    *head = nodeGetNext(nodeToDelete);
    printf("Head word: %s\n",nodeGetWord(*head));
    free(nodeToDelete); 
}

Try drawing it out... I don't know what your functions do exactly, so this makes some assumptions based on the names, but you can get the idea. 尝试将其绘制出来...我不知道您的函数到底能做什么,所以这基于名称进行了一些假设,但是您可以理解。

  1. you pass in head (red 'h') 您在传递head (红色“H”)
  2. you pass in node to delete (blue 'n') 您传入要删除的node (蓝色“ n”)
  3. you set local nextNode to the return of nodeGetNext(node) (I assume that's the node after the one to delete, the green 'nn') 您将本地nextNode设置为nodeGetNext(node)的返回值(我假设这是要删除的节点之后的节点,绿色的“ nn”)
  4. you set nodeToDelete (purple ntd) to node 您将nodeToDelete (紫色ntd)设置为node

在此处输入图片说明

So your code will point head at nodeGetNext(nodeToDelete) . 因此,您的代码将指向nodeGetNext(nodeToDelete) This is actually your unused variable nextNode . 这实际上是您未使用的变量nextNode Then you free nodeToDelete . 然后,您释放nodeToDelete

I'm pretty sure this is not what you wanted to do unless you know that the node to delete is right next to head. 我很确定这不是您要执行的操作,除非您知道要删除的节点就在头旁边。 I think a more normal algorithm would be: 我认为更普通的算法是:

  1. from head search for node to delete 从头开始搜索要删除的节点
  2. set "node to delete"-1 next to "node to delete"+1 在“要删除的节点” +1旁边设置“要删除的节点” -1
  3. delete "node to delete" 删除“要删除的节点”

With speical cases for the Head, or an empty list, etc. 头部有特殊情况,或有一个空白列表等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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