开发者

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. 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. To delete ref, you can write something like

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜