2.3
来源:互联网 发布:军民融合 知乎 编辑:程序博客网 时间:2024/06/10 03:10
Topic: Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
EXAMPLE Input: the node c from the linked list a->b->c->d->d->e
Output: nothing is returned, but the new linked list looks like a->b->d->e
// 关键:考虑要删的节点是head, in the middle, last, empty list.
(1)(2)头和中间节点适用,(3)尾节点:将数据设为某特殊字符,打印时不打印它,(4)空/只有它:直接返回。
// 方法:由于找不到此节点的上一个节点,所以把下一个节点的数据给要删的,下一个的next给这一个的next.实际删了下一个节点,但保留了下一个节点的数据,覆盖了这个节点的数据。(Cannot access the head of the linked list, copy the data from next node over to the current node, delete the next node)
public class List { int data; List next; public List(int d) { this.data = d; this.next = null; } void appendToTail(int d) {//依次在最后一个节点的后面追加元素 List end = new List(d); List n = this; while (n.next != null) {//判断是否是最后一个节点,如果不是,往后移 n = n.next; } n.next = end;//把这个节点设为最后一个节点 } void print() { List n = this; System.out.print("{"); while (n != null) { if (n.next != null) System.out.print(n.data + ", "); else System.out.println(n.data + "}"); n = n.next; } } public static boolean deleteNode(List n){ if(n==null||n.next==null) return false; n.data=n.next.data; n.next=n.next.next; return true; } public static void main(String args[]) { List list = new List(0); list.appendToTail(1); list.appendToTail(5); list.appendToTail(3); list.print(); deleteNode(list.next.next); list.print(); }}
//结果{0, 1, 5, 3}{0, 1, 3}
- 2.3
- 2.3
- 2.3
- 2.3
- 2.3
- 2.3
- 2.3
- 2.3
- Print2Flash 2.3
- 2.3 数据源
- 2.3.5
- 2.3.6
- 2.3 变量
- hdu1.2.3
- 2.3UIPickerView
- CareerCup 2.3
- 2.3 变量
- CareerCup-2.3
- nagios配置文件详解(三个顶力文章合并,深刻理解)
- [20130901]A Short History of Nearly Everything[serial]
- php 5.3 __invoke魔术方法的介绍
- java 错误处理
- 2.2
- 2.3
- 易语言新手入门教程第十四课 - QQ自动登录器第二部分
- 强连通图tarjan算法C语言实现
- Verify
- 2.4
- MST最小生成树及Prim普鲁姆算法
- 2.5
- 声明与定义的理解
- 2.6