您的位置:首页 > Web前端 > Node.js

Leetcode NO.237 Delete Node in a Linked List

2015-07-19 03:12 465 查看
本题题目要求如下:

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.
本题其实是很无聊的,是我在学校Career Fair Blommberg 的题目,当时一出这题,我就跟面试官用我着急的英语讲这是不可能的,因为没有访问前面node的权限。。。然后他说可能做出来。。。然后我就愣神愣了20分钟。。。谁知道这厮说的能做出来就是改变node的value,他还说应该多跟面试官交流。。就算吃一堑长一智吧。。
这题很简单,代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        ListNode* tmp = node->next;
        node->next = node->next->next;
        delete tmp;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: