LeetCode 237. Delete Node in a Linked List

来源:互联网 发布:js判断json对象和数组 编辑:程序博客网 时间:2024/06/16 18:54

Question: 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.

Thought:
At first, i don’t understand since it didn’t give us the first node. Looking for the website, it seems that as long as you change this current node to the next node, it would be fine. I tried, and it worked!

But i still don’t understand, how about the next one? If we delete node 2 rather than 3, would it the list become 1->3->3->4, then i realized that it won’t since node 2’s pointer is pointing 4 now.

So the code:

 /** * 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) {        if(node==NULL) {}        else{            node->val=node->next->val;            node->next=node->next->next;         }    }};

will lead node 3 no one point to, although it pass the test.
So the following would be better:

class Solution {public:    void deleteNode(ListNode* node) {        if(node==NULL) {}        else{            ListNode *temp=node->next;            node->val=temp->val;            node->next=temp->next;            delete temp;        }    }};

Notes: difference between -> and .

  • -> for accessing object member variables and methods via pointer to object

Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();

  • . for accessing object member variables and methods via object
    instance

Foo foo;
foo.member_var = 10;
foo.member_func();

Link: http://stackoverflow.com/questions/11902791/what-is-the-difference-between-and-in-c

0 0
原创粉丝点击