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
- leetcode: Delete Node in a Linked List
- LeetCode Delete Node in a Linked List
- 【leetcode】Delete Node in a Linked List
- Leetcode: Delete Node in a Linked List
- [LeetCode]Delete Node in a Linked List
- 【leetcode】Delete Node in a Linked List
- Leetcode Delete Node in a Linked List
- LeetCode || Delete Node in a Linked List
- [LeetCode] Delete Node in a Linked List
- LeetCode-Delete Node in a Linked List
- 【leetCode】Delete Node In A Linked List
- [leetcode] Delete Node in a Linked List
- [LeetCode]Delete Node in a Linked List
- [leetcode]Delete Node in a Linked List
- Leetcode: Delete Node in a Linked List
- LeetCode Delete Node in a Linked List
- LeetCode-Delete Node in a Linked List
- leetcode | Delete Node in a Linked List
- how to make custom table cell
- 4-1 单链表逆转 (20分)
- Notes: Process in Operation System and Dead Lock 操作系统中的进程和死锁问题
- rem自适应布局-移动端自适应必备
- 4-2 顺序表操作集 (20分)
- LeetCode 237. Delete Node in a Linked List
- 4-3 求链式表的表长
- 安装auto-fu.zsh让命令输入自动补全
- 4-4 链式表的按序号查找 (10分)
- 4-5 链式表操作集 (20分)
- 第13章 文件读写的相关要点记录--二进制与文本文件
- Data Quality Services
- NYOJ 1058.部分和问题(深搜)
- dialog_sneakbar_toas