LeetCode 237. Delete Node in a Linked List

来源:互联网 发布:淘宝店怎么设置限购 编辑:程序博客网 时间:2024/06/05 06:10

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.

本题涉及单向链表的知识,很多数据结构都涉及增、删、查、改四项基本操作,单链表的删除结点的操作相对而言是比较简单的。

单链表节点的删除操作,直接将要删除的结点的值替换成直接后继的值,并将尾指针指向直接后继的尾指针指向的位置,如果要删除结点是尾结点,直接将结点的直接前驱的尾指针指向null,本题不考虑尾指针删除问题,代码非常简单。

Java代码如下:

/** * 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) {        node.val = node.next.val;        node.next = node.next.next;    }}


0 0
原创粉丝点击