Leetcode: Delete Node in a Linked List
2015-07-16 23:30
477 查看
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
比较水的题,有点投机取巧。直接把值替换一下。
/**
* 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 == nullptr || node->next == nullptr) {
return;
}
node->val = node->next->val;
node->next = node->next->next;
}
};
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 -> 4and you are given the third node with value
3, the linked list should become
1 -> 2 -> 4after calling your function.
比较水的题,有点投机取巧。直接把值替换一下。
/**
* 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 == nullptr || node->next == nullptr) {
return;
}
node->val = node->next->val;
node->next = node->next->next;
}
};
相关文章推荐
- [C/C++]反转链表
- C#实现基于链表的内存记事本实例
- C语言实现带头结点的链表的创建、查找、插入、删除操作
- C++实现简单的学生管理系统
- Linux内核链表实现过程
- C++链表倒序实现方法
- C#通过链表实现队列的方法
- 找出链表倒数第n个节点元素的二个方法
- Java数据结构之简单链表的定义与实现方法示例
- C语言单循环链表的表示与实现实例详解
- C++实现的链表类实例
- PHP小教程之实现链表
- C语言双向链表的表示与实现实例详解
- C语言实现输出链表中倒数第k个节点
- C++语言实现线性表之链表实例
- STL list链表的用法详细解析
- C语言创建链表错误之通过指针参数申请动态内存实例分析
- php链表用法实例分析
- JavaScript中数据结构与算法(三):链表
- 编码实现从无序链表中移除重复项(C和JAVA实例)