/**
* @Description
*/
public class Test16 {
public class ListNode{
int val;
ListNode next;
public ListNode(int value,ListNode nextNode) {
val=value;
next=nextNode;
}
}
//leetcode简化版本
public ListNode deleteNode(ListNode head, int val) {
if (head.val == val) return head.next;
ListNode pre = head;
ListNode cur = head.next;
while (cur != null && cur.val != val){
pre = cur;
cur = cur.next;
}
if (cur != null){
pre.next = cur.next;
}
return head;
}
//剑指offer版本
public ListNode deleteNode(ListNode head,ListNode pToBeDeleted) {
if(head==null||pToBeDeleted==null)
return head;
//待删除结点不是尾结点
if(pToBeDeleted.next!=null) {
ListNode nextNode=pToBeDeleted.next;
pToBeDeleted.val=nextNode.val;
pToBeDeleted.next=nextNode.next;
nextNode=null;
//只有一个结点(即是尾结点,又是头结点)
}else if(head==pToBeDeleted) {
pToBeDeleted=null;
head=null;
//链表含多个结点,删除尾结点
}else {
ListNode preNode=head;
while(preNode.next!=pToBeDeleted && preNode!=null) {
preNode=preNode.next;
}
if(preNode==null) {
return head;
}
preNode.next=null;
pToBeDeleted=null;
}
return head;
}
public static void main(String[] args) {
}
}
剑指Offer-15-删除链表中某个节点
最新推荐文章于 2022-04-11 17:18:37 发布