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}



 

 

 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 斜挎包包磨衣服怎么办 电脑ip被别人知道了怎么办 西乐葆不止痛了怎么办 家里鸽子多捣蛋的不行怎么办 联璧倒闭了理财钱怎么办 众筹平台雷了怎么办 App理财无法提现怎么办 喝咖啡喝的心慌怎么办 睾丸被用力捏破流血怎么办 足球大师球队声望过高怎么办 fm17买了好多球员怎么办 fm2018电脑适应了战术怎么办 家纺摆放跑色怎么办 买的t恤太小了怎么办? 汽车全包围脚垫翘边怎么办 针织衣服线跑了怎么办 老板跟老板娘吵架我应该怎么办 偷看老板娘洗澡被发现怎么办? 幽浮2人挂了怎么办 蜻蜓fm业务扣费怎么办 退出键退不到主页面怎么办 3d纯英文版怎么办 3d单位设置错了怎么办 翼龙贷款不还款怎么办 lol视角变低了怎么办 王者荣耀体验卡太多怎么办 文件打开后超出电脑屏幕怎么办 2400g玩lol跳fps怎么办 手机吃鸡延迟长怎么办 三星s8发热卡顿怎么办 逆水寒修为不够怎么办 诛仙摆摊金币被扣怎么办 诛仙手游宠物亲密度满了怎么办 诛仙包裹满了怎么办 感觉自己心理有问题 怎么办 刺激战场手机配置低怎么办 国土防线2没反应怎么办 镜之边缘迷路了怎么办? 陌陌直播不清晰怎么办 夏利n5 1.0费油怎么办 gg修改器是病毒怎么办