简体   繁体   English

我需要删除链表中的节点,如何找到它之前的节点,以便重新排列列表?

[英]I need to delete a node in a linked list, how do I find the node that comes BEFORE it so I can rearrange the list?

It's for a school assignment. 这是为了学校作业。 I have to use a search method that returns the node that I search for or the one right before it if it doesn't exist. 我必须使用一个搜索方法,它返回我搜索的节点或它之前的节点(如果它不存在)。 Obviously if I want to delete a node it'll return that one node and I won't be able to find the one that comes before it. 显然,如果我想删除一个节点,它将返回一个节点,我将无法找到它之前的节点。 Here's the code for the search method: 这是搜索方法的代码:

private myNode search(myEntry searchEntry)
{
  myNode ref = first;
  myNode pre = null;

  while(ref != null)
  {
     if(searchEntry.compareTo(ref.data) < 0)
        break;
     pre = ref;
     ref = ref.link;
  }
  return pre;
}

first is the first node, ref is the pointer, pre is the node preceding the pointer. 第一个是第一个节点,ref是指针,pre是指针前面的节点。 Maybe I'll use a doubly-linked list if it doesn't require me to rewrite things too much but if there's a simple way to find the predecessor of the node I'm trying to delete using this search method then I'd like to know. 也许我会使用双链表如果它不需要我重写太多但是如果有一个简单的方法来找到我尝试使用这种搜索方法删除的节点的前身那么我会喜欢知道。 I'm not supposed to be using doubly-linked lists at all. 我根本不应该使用双向链表。

You can't do that with your search method. 您无法使用搜索方法执行此操作。 You have to implement a distinct search method that return the predecessor of the node and then delete it. 您必须实现一个独特的搜索方法,该方法返回节点的前任,然后将其删除。

If you need to delete ref, than you return pre. 如果你需要删除ref,那么你需要先删除。 To delete ref, you can write something like 要删除ref,您可以编写类似的内容

pre = list.search(entry); //find the prescending node
ref = pre.link;           //get the node you want to delete
pre.link = ref.link;      //reassign link
ref.delete();             //delete node

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

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