下面是我的方法,它显示了我如何尝试从链表中删除节点。添加了完整的实现,包括节点和我如何创建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;
}
}
您要删除第一个节点吗?那为什么不这样做呢
我不知道你的代码结构,但这可以帮助你:
public void RemoveFirst() {
this.Head = Head.Next();
this.Size -= 1;
}
始终记得跟踪列表的大小