public class DeleteNode { public static void main(String[] args){ Solution18 solution18 = new Solution18(); ListNode18 head = solution18.initLinkList(new ListNode18()); ListNode18 toBeDeleted = head; while(toBeDeleted.next!=null){ toBeDeleted=toBeDeleted.next; } solution18.printLinkList(head); solution18.deleteNode(head,toBeDeleted); solution18.printLinkList(head); } } class ListNode18{ int value; ListNode18 next; } class Solution18{ //初始化链表 ListNode18 initLinkList(ListNode18 head){ ListNode18 p=head; p.value=-1; for(int i=0; i<10; i++){ ListNode18 nextNode = new ListNode18(); nextNode.value=i; p.next=nextNode; p=nextNode; } return head; } //打印链表 void printLinkList(ListNode18 p){ while (p.next!=null){ System.out.print(p.value+ " "); p=p.next; } System.out.print(p.value); System.out.println(); } void deleteNode(ListNode18 listHead,ListNode18 toBeDeleted){ if(listHead ==null || toBeDeleted ==null){ return; } //如果要删除的结点不是最后一个结点 if(toBeDeleted.next!=null){ ListNode18 listNode18= toBeDeleted.next; toBeDeleted.value=listNode18.value; toBeDeleted.next=listNode18.next; listNode18.next=null; }else if(listHead == toBeDeleted){//链表只有一个节点 listHead=null; toBeDeleted=null; }else{//链表有多个节点,删除尾节点 ListNode18 p=listHead; while(p.next != toBeDeleted){ p=p.next; } p.next=toBeDeleted.next; toBeDeleted.next=null; } } }