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

Delete Node in a Linked List

时间:2015-12-14 23:03:59      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/delete-node-in-a-linked-list/

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.

解题思路:

仅给出当前结点,要删除。方法就是将后面结点的值赋予当前结点,然后删除后一个结点。因为主要为了熟悉C++,具体实现还有些探讨。

/**
 * 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) {
        int temp = node->next->val;
        node->next->val = node->val;
        node->val = temp;
        node->next = node->next->next;
    }
};

首先,事实上不需要交换值,仅需要赋值就可以了。所以两行就可以了。

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

另外,在C++,还要注意释放内存。可以加上delete。

还有更简单的。

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

为啥这样也行?node是一个指针,存储的是一个内存地址,那么*的意义就是对应node内存地址的值。*node=*(node->next)可以直接将node这个内存地址对应的值改写为node->next,这样可以直接改写内存!想想和Java有何不同?Java里任何一个变量其实都是一个指针,但是只能改变它的指向,而不能直接改变他指向那块内存的值。比如ObjectA = B,就是将A指向B,但是原来A指向那块内存的值,你是无论如何都改变不了的,这点C++用*就完全可以办到。

Delete Node in a Linked List

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/5037652.html

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