237. 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 value3, the linked list should become 1 -> 2 -> 4 after calling your function.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution 
{
    public void deleteNode(ListNode node) 
    {
        
    }
}

Solution:

咋一看这道题感觉就是最基本的链表操作,刚准备动手发现并不能访问链表本身(并没有给出链表的头结点),又由于单链表没有前向指针,所以不能用简单的删除节点的思路。

参考Discuss后得到思路:

  1. 判断待删除的node是否是最后一个node,如果是则直接将最后一个节点删除(虽然该该题目指明不需要考虑链表中的最后一个节点,但考虑有最后一个节点的情况更为周全)。Java似乎无法实现删除最后一个节点,无法将所有指向最后一个节点的引用置为null(一共有两个引用指向最后一个节点,分别是该函数的参数node,和最后一个节点的前驱节点的next)。如果用C/C++则可以直接调用delete运算符。
  2. (如果不是最后一个节点)将后一个节点的val拷贝到当前节点val,然后删除后一个节点(将当前节点的next指向null

code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution 
{
    public void deleteNode(ListNode node) 
    {
        if(node.next == null)  // this part is useless according to the requirement and Java
            node = null;  // in C++ we can delete node;
        else
        {
            node.val = node.next.val;
            node.next = node.next.next;
        }
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容