Leetcode NO.237 Delete Node in a Linked List

来源:互联网 发布:js鼠标经过特效 编辑:程序博客网 时间:2024/06/05 04:52

本题题目要求如下:

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 -> 4after 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;    }};


0 0
原创粉丝点击