有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我不能用这段代码从链表中删除第一个节点?

下面是我试图从链表中删除节点的方法。添加了完整的实现,包括节点和如何创建linkedlist

class Node {
    int val;
    Node next;
    Node(int n){
        this.val = n;
    }
}
Public class LinkedList {

public static void main(String[] args) {
        int[] inp = {100,3,1,50,25};
        Node head = createLinkedList(inp);
        displayList(head);
        System.out.println("List after the node is removed:");
        removeNode(head,100);
        displayList(head);
}

static void removeNode(Node head, int val) {
        Node sentinal = new Node(-1);
        sentinal.next = head;
        Node prev = sentinal;
        while(head!=null){
            if(head.val==val){
                prev.next = head.next;
                return;
            }
            prev=head;
            head=head.next;
        }
    }

static Node createLinkedList(int[] inp){
        Node head = new Node(-1);
        Node temp = head;
        for(int n:inp){
            temp.next = new Node(n);
            temp = temp.next;
        }
        return head.next;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    您要删除第一个节点吗?那为什么不这样做呢
    我不知道您的代码结构,但这可以帮助您:

    public void RemoveFirst() {
            this.Head = Head.Next();
            this.Size -= 1;
        }
    

    始终记住跟踪列表的大小