删除给定节点之前的节点

时间:2018-09-30 14:18:49

标签: java data-structures

我具有删除特定节点的代码,但是无法删除给定节点之前的节点。关于如何使用此功能的任何想法? (以下解决方案)

void deleBefore(Node q) {
    if (q == null || q == head) {
        return;
    }

    Node p = null;
    Node n = head;
    while (n != null && n.next != q) {
        p = n;
        n = n.next;
    }
    if (n == null) {
        return;
    }

    if (n == head) {
        head = q;
    } else {
        p.next = q;
    }

节点类

public class Node {

Boat info;
Node next;

Node() {
}

Node(Boat x, Node p) {
    info = x;
    next = p;
}

Node(Boat x) {
    this(x, null);
}

}

2 个答案:

答案 0 :(得分:0)

我修改了您的功能,希望对您有所帮助

 void deletePrev(Node q)
 {if(q==null || q==head) return;

  Node p=head;
  while(p!=null && p.next.next!=q) p=p.next;
  if(p==null) return; // q is not in the list
  p.next = q;
  if(p.next.next==null) tail = p;
 }

答案 1 :(得分:0)

在遍历列表以查找q时,您需要跟踪上一个节点,如果找到了next,则将其q更新为q,或更新head

void deleteBefore(Node q)
{
  if(q == null || q == head) return;

  Node p = null;
  Node n = head;
  while(n != null && n.next != q)
  {
    p = n;
    n = n.next;
  }
  if(n == null) 
    return;

  if(n == head) 
    head = q;
  else 
    p.next = q;
}