删除链接列表C ++中的节点 [英] Deleting Node in Linked List C++

查看:127
本文介绍了删除链接列表C ++中的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在搜索论坛,但仍然非常新的语言和链接列表,所以我几乎不能破译的结果。

So I've been searching forums, but im still very new to the language and linked lists so I can barely decipher the results.

基本上我做了一个删除函数为我的链表。
我当前可以创建一个列表,遍历列表,排序列表,搜索列表,并在链接列表中的任何节点之前插入。我回收了一些代码从插入,以定位在列表中的点,我可以删除。我的主要困惑点是如何将以前的点链接到正在删除的节点之后的节点。

basically I made a delete function for my linked list. I can currently Create a list, traverse the list, sort the list, search the list, and insert before any node in the linked list. I recycled some code from the insert to locate the point in the list where I could delete. My main point of confusion is how to link the previous points to the node that is after the one I am deleting.

推荐答案

不会写一个全新的链表实现,但我可以指出一些你的代码的问题。

I won't write a whole new linked list implementation but i can point out some of the problems with the code for you.


The trick is to stay one node ahead of the one you want to delete.

我已重命名条目当前清楚

nodetype *current , *first, *next;
int akey;

// With this line your search will start from the second element.
// current =start->ptr;
// Should be
current = start;

// this is not needed. I am assuming the last node has NULL value for '->ptr'
// last=start;
next = current->ptr;

cout<<"Input Data You Would Like To Delete"<<endl;
cin>>akey;

// Check if the first node contains the data
// Assuming the list will have at least one element. i.e. current is not NULL 
while (current->adata == akey)
{
  // Delete it.
  delete current;
  // Update current for the while loop
  current = next;
  // update next too.
  next = current->ptr;
}
// Now we know the first element doesn't contain the data.
// Update the pointer to the begging of the new list if anything is removed from the top.
first = current;

// This has unnecessary checks. 
// ****Specifically (akey!=current->adata) will 
// prevent you from entering the loop if it is false.
// while((akey!=current->adata)&&(current->ptr !=NULL))
while(next != NULL)  // This should be enough
{
     if(next->adata == akey)
     {
          // make the current node (before the 'deletion point') 
          // lined to the one after the 'deletion point (next of the next)
          current->ptr = next->ptr; 
          // delete the node. 
          delete next;
          // Make the next pointer point to the new next. 
          next = current->ptr
     }
    // Otherwise advance both current and next.
     else {
           current = next;
           next = next->ptr; 
     }
}

// Use this to test it.
current = first;
while(current){
    cout<<current->adata<<", ";
    current = current->ptr;
}

这不是最干净的方法。但它与您的实现类似,因此您可以看到哪里错了。

This is not the cleanest way. However it is similar to your implementation so you can see where you went wrong.

这篇关于删除链接列表C ++中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆