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

删除单向链表的一个节点,只给出了要删除的节点。

思路:从要删除的节点的下一个节点开始,逐一覆盖前面的节点的值,注意要删除最后一个多余的节点(Java中指向空即可,等待垃圾回收)。

代码:

/**
* 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) {
ListNode iNode = node;
while(iNode.next != null) {
//覆盖当前节点的值
iNode.val = iNode.next.val;
//删除最后一个多余的节点
if(iNode.next.next == null) {
iNode.next = null;
break;
}
iNode = iNode.next;
}
}
}

最新文章

  1. shell 随机从数组中抽取三个随机数(#可持续不停抽取)
  2. asp.net各种cookie代码和解析
  3. html5语义标签
  4. Android课程---帧布局 FrameLayout
  5. MyEclipse 10 中如何更改字体
  6. 09-排序3 Insertion or Heap Sort
  7. 【转】eclipse新建项目,报错“Error: workspace\appcompat_v7\res\values-v21\styles_base.xml No resource found that matches the given name”
  8. BZOJ 1739: [Usaco2005 mar]Space Elevator 太空电梯
  9. python 之调用Linux shell命令及相关高级应用
  10. python+selenium安装
  11. SSIS 处理 bit 列
  12. 【vue】vue +element 搭建项目,将js函数变成vue的函数
  13. Fluent动网格【5】:部件变形
  14. yum的配置文件介绍
  15. docker简易命令
  16. mvc手把手教你写excel导入
  17. [Node.js] Level 2 new. Event
  18. openerp 7.0 来自外部的邮件会发送二次问题解决方法
  19. 20181009-3 选题 Scrum立会报告+燃尽图 02
  20. 大公司怎么做Android代码混淆的?

热门文章

  1. maven_nexus3私服搭建
  2. win10无法访问局域网共享文件?(因微软账户和本地账户登陆问题导致)
  3. div 背景自适应
  4. .net 高级写法总结
  5. ThinkPHP3.2 介绍
  6. Oracle数据库表空间与用户的关系是 ( )
  7. html -- <meta name="viewport"/>
  8. PHPOffice下PHPWord生成Word2007(docx)使用方法
  9. 最短路径问题-Floyd算法
  10. 【Java面试题】34 List 、Map、Set 区别?