码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode笔记:237. Delete Node in a Linked List

时间:2016-03-29 10:37:30      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

大意:

写一个函数来删除一个简单链表中的一个节点(除了尾节点),只给出这个节点。
假设有一个链表 1->2->3->4,并给你第三个值为3的节点,在调用你的函数之后这个链表应该变成1->2->4。

思路:

一般我们删除一个链表节点,直接将其上一个节点的next指向其下一个节点就可以了,但是这里只给出了该节点本身,也就是说你只能获取到该节点本身以及其下一个节点。那么就只能将该节点直接变成下一个节点了,将其值设为下一个节点的值,将其next指向下一个节点的next,就可以了。

代码(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;
    }
}

代码(C++):

/**
 * 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 = *node->next;
    }
}

疑问:

用Java像C++那样,直接将 node = node.next 将不能ac,必须对其val和next分别设置,这是为什么呢?希望高手帮忙解答一下~

版权所有:http://blog.csdn.net/cloudox_

LeetCode笔记:237. Delete Node in a Linked List

标签:

原文地址:http://blog.csdn.net/cloudox_/article/details/51000593

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!