剑指 Offer 18. 删除链表的节点
遍历
public class Solution {public ListNode deleteNode(ListNode head, int val) {// 如果是空链表,直接返回空if (head == null) return null;// 如果要删除的节点是第一个,直接返回 head.nextif (head.val == val) return head.next;// 记录前一个节点ListNode pre = head;// 记录当前节点ListNode cur = head.next;while (true) {// 如果当前节点是要删除的节点if (cur.val == val) {// 令上一个节点的 next 指向当前节点的 next,停止循环pre.next = cur.next;break;}// 往前进一步pre = pre.next;cur = cur.next;}return head;}}
遍历,增加伪头节点
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:37.5 MB, 在所有 Java 提交中击败了93.76%的用户
class Solution {public ListNode deleteNode(ListNode head, int val) {// 使用伪头节点ListNode temp = new ListNode(0);temp.next = head;// 记录前一个节点ListNode pre = temp;// 记录当前节点ListNode cur = temp.next;while (true) {// 如果当前节点是要删除的节点if (cur.val == val) {// 令上一个节点的 next 指向当前节点的 next,停止循环pre.next = cur.next;break;}// 往前进一步pre = pre.next;cur = cur.next;}return temp.next;}}
递归
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:37.8 MB, 在所有 Java 提交中击败了66.79%的用户
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head == null) return null;
if (head.val == val) return head.next;
else head.next = deleteNode(head.next, val);
return head;
}
}
