原题链接:https://leetcode.com/problems/delete-node-in-a-linked-list/
题目描述:
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4
and you are given the third node with value 3
,
the linked list should become 1 -> 2 -> 4
after calling your function.
思路:
删除链表结点有两种思路,一、改变指针指向,不改变结点值 ,二、改变结点值
条件只给了要删除结点p的指针,没有给出头结点,所以不能得到p的前结点pre,也就无法简单的让pre指向p后面的结点完成删除p的操作。
所以只能通过结点值的操作达到删除的目的。注意,这种方法不能删除最后一个结点(能删头结点)。幸运的是,题目只要求删除中间结点。
算法:
[java] view
plain copy
- public void deleteNode(ListNode node) {
- ListNode pre = node, p = node;
- while (p.next != null) {// 当p不是最后一个结点时
- p.val = p.next.val;
- pre = p;
- p = p.next;
- }
- pre.next = null;// 此时pre指向倒数第二个结点
- }
时间: 2024-08-14 03:55:40