LeetCode Delete Node in a Linked List
2015-07-15 18:02
369 查看
Description:
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
with value
Solution:
既然这里直接给的是需要去掉的node,前一个node的next指针无法得到,所以这里不能用修改指针的方法;可以用直接修改值的方法。
需要注意的一个细节,next=temp.next;在最后设置next为tail的时候,一定要用temp.next=null;而不能是next=null。因为前者仅仅是修改了next指针指向的内容,temp.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.
Solution:
既然这里直接给的是需要去掉的node,前一个node的next指针无法得到,所以这里不能用修改指针的方法;可以用直接修改值的方法。
需要注意的一个细节,next=temp.next;在最后设置next为tail的时候,一定要用temp.next=null;而不能是next=null。因为前者仅仅是修改了next指针指向的内容,temp.next还是指向原来的内存空间。
import java.util.*; public class Solution { public void deleteNode(ListNode node) { ListNode temp = node, next; while (temp != null) { next = temp.next; if (next != null) { temp.val = next.val; if (next.next == null) { System.out.println(next.val + " end"); temp.next = null; break; } } temp = next; } } }
相关文章推荐
- nodejs express3.x 与 express4.x 的router区别 与修改方法
- Ubuntu 14.04下hadoop 2.2.0 伪分布环境配置datanode不能启动的解决办法
- 【排错】Failed to replace a bad datanode on the existing pipeline due to no more good ...
- 用MindNode描述了一个小项目思路
- LeetCode#237 Delete Node in a Linked List
- 【LeetCode 237】Delete Node in a Linked List
- 【LeetCode】237. Delete Node in a Linked List
- How to download a file with Node.js?
- Swap Nodes in Pairs
- leetcode 237: Delete Node in a Linked List
- Connect is a middleware layer for Node.js
- [leetcode] 237.Delete Node in a Linked List
- [LeetCode] Delete Node in a Linked List
- leetcode[237]:Delete Node in a Linked List
- Java 开发者如何入门 Node.js 英文原文:Getting Started with Node.js for the Java Developer
- 基于NodeJS的全栈式开发(基于NodeJS的前后端分离)
- Leetcode 237 Delete Node in a Linked List
- 在Java项目中拥抱Nodejs — 使用gruntjs编译typescript,并将生成的js合并、压缩
- 升级nodejs
- 【Eclipse高速发展-文章插件】google V8,对于调试Nodejs