【Leetcode】Delete Node in a Linked List
2016-06-07 20:33
357 查看
原题链接:https://leetcode.com/problems/delete-node-in-a-linked-list/
题目描述:
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
思路:
删除链表结点有两种思路,一、改变指针指向,不改变结点值 ,二、改变结点值
条件只给了要删除结点p的指针,没有给出头结点,所以不能得到p的前结点pre,也就无法简单的让pre指向p后面的结点完成删除p的操作。
所以只能通过结点值的操作达到删除的目的。注意,这种方法不能删除最后一个结点(能删头结点)。幸运的是,题目只要求删除中间结点。
算法:
[java] view
plain copy
public void deleteNode(ListNode node) {
ListNode pre = node, p = node;
while (p.next != null) {// 当p不是最后一个结点时
p.val = p.next.val;
pre = p;
p = p.next;
}
pre.next = null;// 此时pre指向倒数第二个结点
}
题目描述:
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.
思路:
删除链表结点有两种思路,一、改变指针指向,不改变结点值 ,二、改变结点值
条件只给了要删除结点p的指针,没有给出头结点,所以不能得到p的前结点pre,也就无法简单的让pre指向p后面的结点完成删除p的操作。
所以只能通过结点值的操作达到删除的目的。注意,这种方法不能删除最后一个结点(能删头结点)。幸运的是,题目只要求删除中间结点。
算法:
[java] view
plain copy
public void deleteNode(ListNode node) {
ListNode pre = node, p = node;
while (p.next != null) {// 当p不是最后一个结点时
p.val = p.next.val;
pre = p;
p = p.next;
}
pre.next = null;// 此时pre指向倒数第二个结点
}
相关文章推荐
- Sublime text 2/3 中 jade语法高亮
- nodejs MODEL层 封装(二)
- nodejs2
- windows 10 安装 hexo 续
- ActiveMQ + NodeJS + Stomp 入门
- node 获取本地IP地址
- 创建 Web 前端开发环境(node和npm)
- Populating Next Right Pointers in Each Node II
- window下安装node.js
- 如何在 Windows 10 中搭建 Node.js 环境?
- 如何在 Windows 10 中搭建 Node.js 环境?
- Populating Next Right Pointers in Each Node
- Delete Node in a Linked List
- NodeJS实现WebSocket,太容易了吧!!
- leetcode 25. Reverse Nodes in k-Group
- Node.js child_process模块中的spawn和exec方法
- window10 安装 hexo
- node.js 监听文件变化并打印
- Node.js(安装包版)、Sublime text3安装与配置
- 19. Remove Nth Node From End of List