Delete a node, only give access to that node.
2016-06-12 00:15
429 查看
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
the linked list should become
思路:Only access to that node, we can copy the value of next node to that node, and point to the next.next;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
if(node == null || node.next == null) {
return;
}
ListNode next = node.next;
node.val = next.val;
node.next = next.next;
return;
}
}
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.
思路:Only access to that node, we can copy the value of next node to that node, and point to the next.next;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
if(node == null || node.next == null) {
return;
}
ListNode next = node.next;
node.val = next.val;
node.next = next.next;
return;
}
}
相关文章推荐
- Node.js之Express三
- bug:配置secondarynamenode && 斯塔尼亚聊天记录
- bug:datanode启动后立刻死掉:java.io.IOException: Incompatible clusterIDs in....
- Node.js(插件包)、Sublime text3安装与配置
- Node.js服务器端编程实践(一):服务器创建与hello world应答
- Openstack组建部署 — Environment of Controller Node
- Node.js and the new web front-end
- Range——插入对象insertNode
- node安装相关
- leetcode 117 Populating Next Right Pointers in Each Node II
- leetcode 116 Populating Next Right Pointers in Each Node
- nodemcu的gpio相关操作
- 使用淘宝镜像访问node包
- 将单链表中相邻两节点对换
- Datanode JPS
- Node.js基本语法简介
- leetcode 19. Remove Nth Node From End of List
- 117. Populating Next Right Pointers in Each Node II
- 116. Populating Next Right Pointers in Each Node
- Node.js: exports与module.exports的区别