Leetcode 237. Delete Node in a Linked List

来源:互联网 发布:java 数组长度 long 编辑:程序博客网 时间:2024/05/02 05:02

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_prev.next=p_prev.next.next,来删除该节点。在这道题里需要用到逆向思维,即先将下一个节点的值赋给删除节点,然后删除下一个节点即可。代码如下:

/** * 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;    }}
1 0
原创粉丝点击