开发者社区> 问答> 正文

如何删除双链表的第一个节点

我有一个双向链表的实现,并且我试图删除给定位置的特定节点。我设法将第二个节点删除到最后一个节点,但是当我尝试删除第一个节点失败时,我想知道我的代码出了什么问题。 head.next.previous = null; head = head.next; 这是我的代码

public class Proses { private class Node{ String Matkul; int NilaiUts; int NilaiUAS; Node previous;
Node next;

    public Node(String Matkul, int Nilai, int NilaiUAS) {
        this.Matkul = Matkul;
        this.NilaiUts = Nilai;
        this.NilaiUAS = NilaiUAS;
    }  
}  

Node head, tail = null;    
public void addNode(String matkul, int Nilai, int NilaiUAS) {   
    Node newNode = new Node(matkul, Nilai, NilaiUAS);   
    if(head == null) {   
        head = tail = newNode;    
        head.previous = null;  
        tail.next = null;  
    } else {  
        tail.next = newNode;   
        newNode.previous = tail;  
        tail = newNode;  
        tail.next = null;  
    }  
}  

public void delete(int position){
    if (head == null || n <= 0) 
        return; 
    Node current = head; 
    int i; 
    for (i = 1; current != null && i < position; i++) 
    { 
        current = current.next; 
    } 
    if (current == null) 
        return; 
    deleteNode(head, current); 
}

//delete function
public Node deleteNode(Node head, Node del){
    if (head == null || del == null){
        return null; 
    }
    if (head == del){
        head = del.next;
        del.next.previous = null;
    }
    if (del.next != null){
        del.next.previous = del.previous; 
    }
    if (del.previous != null){
        del.previous.next = del.next; 
    }
    del = null; 
    return head; 
}

}

展开
收起
小六码奴 2019-10-14 19:12:28 8789 0
1 条回答
写回答
取消 提交回答
  • 使用你的代码,如果场景以一个节点结束(头将指向该节点)并且你要删除该节点(即头),则代码将失败,并出现NullPointerException

    del.next.previous = null; 因为del.next为NULL;

    可以看下面的代码从双链表中删除一个节点

    // Function to delete a node in a Doubly Linked List. 
    // head_ref --> pointer to head node pointer. 
    // del --> data of node to be deleted. 
    void deleteNode(Node head_ref, Node del) 
    { 
    
        // Base case 
        if (head == null || del == null) { 
            return; 
        } 
    
        // If node to be deleted is head node 
        if (head == del) { 
            head = del.next; 
        } 
    
        // Change next only if node to be deleted 
        // is NOT the last node 
        if (del.next != null) { 
            del.next.prev = del.prev; 
        } 
    
        // Change prev only if node to be deleted 
        // is NOT the first node 
        if (del.prev != null) { 
            del.prev.next = del.next; 
        } 
    
        // Finally, free the memory occupied by del 
        return; 
    } 
    

    代码参考:https://www.geeksforgeeks.org/delete-a-node-in-a-doubly-linked-list/

    2019-10-14 19:13:47
    赞同 展开评论 打赏
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载