Delete Node in a Linked List

来源:互联网 发布:飞鸟p2p网络理财 编辑:程序博客网 时间:2024/05/22 14:07

Description:

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

问题描述:

编写一个函数来删除单链表中的一个节点(尾部除外),只给定该节点的访问权限。

Ex:

Supposed the linked list is 1 -> 2 -> 3 -> 4and you are given the third node with value 3, the linked list should become1 -> 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) {        node.val=node.next.val;        node.next=node.next.next;    }}
0 0
原创粉丝点击