剑指 Offer 18. 删除链表的节点
剑指 Offer 18. 删除链表的节点
Offer 18
- 本题就是简单的单链表删除节点的题目,需要处理边界的处理以及需要删除的结点是否是头结点。
package com.walegarrett.offer;
/**
* @Author WaleGarrett
* @Date 2021/1/25 21:41
*/
public class Offer_18 {
/**
* 单链表结点的定义
*/
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode deleteNode(ListNode head, int val) {
if(head == null)
return null;
ListNode pre = null, current;
current = head;
while(current != null){
if(current.val == val){
if(pre == null){//表示要删除的是头结点
head = current.next;
}else{
pre.next = current.next;
}
break;
}
pre = current;
current = current.next;
}
return head;
}
}
Either Excellent or Rusty