链表的头删分为空链表和非空链表两种情况,对于空链表,链表中一个节点都没有,所以无法删除,返回null,对于非空链表,头删就是让head(头节点)指向head的下一个节点,这样原来的头节点就被删除,此时head指向的节点就是删除原来头节点之后的头节点,直接返回现在的head即可。
public class Node {
int val;
Node next=null;
Node(int val){
this.val=val;
}
}
public class PopFront {//链表的头删
public static Node popFront(Node head){
//空链表
if(head==null){
System.out.println("空链表无法删除");
return null;
}
//走到这里说明链表非空
head=head.next;//直接将head指向head的下一个
return head;
}
public static void Print(Node head){
Node cur=head;
while(cur!=null){
System.out.print(cur.val+"-->");
cur=cur.next;
}
}
public static void main(String[] args){
Node l1=new Node(1);
Node l2=new Node(2);
Node l3=new Node(3);
Node l4=new Node(4);
Node l5=new Node(5);
l1.next=l2;
l2.next=l3;
l3.next=l4;
l4.next=l5;
l5.next=null;
System.out.print("头删前:");
Print(l1);
System.out.println("null");
System.out.print("头删后:");
Print(popFront(l1));
System.out.println("null");
}
}