• Cracking the coding interview--Q2.3


    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->e
    Result: nothing is returned, but the new linked list looks like a- >b- >d->e

    删除链表中的一个节点,但并没有给出链表的头结点,而是只能访问要删除的这个节点。

    解答:

    将待删除的下一个节点copy到当前节点,然后删除下一个节点。要单独考虑待删除的是链表尾或者链表头的情况。链表头没有特别影响,而如果是链表尾的话,一开始想的是直接将该节点赋值为null,但是测试时发现没有效果。 看书中说如果是链表尾是不能删除的,要向面试官指出这个问题,或者将该节点的数据标记成一个特殊的值表示这个节点是个虚假不用的节点。

    public class Main {
        public static void appendToTail(List head, int d) {
            List end = new List(d);
            List n = head;
            while (n.next != null) {
                n = n.next;
            }
            n.next = end;
        }
    
        public static void print(List head) {
            List n = head;
            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 revomeNode(List node) {
            if (node == null || node.next == null) {
                return false;
            } else {
                node.data = node.next.data;
                node.next = node.next.next;
                return true;
            }
        }
    
        public static void main(String args[]) {
            List list = new List(0);
            appendToTail(list, 1);
            appendToTail(list, 2);
            appendToTail(list, 3);
            appendToTail(list, 4);
            appendToTail(list, 5);
            appendToTail(list, 6);
            appendToTail(list, 7);
            appendToTail(list, 8);
            appendToTail(list, 9);
            print(list);
            List node = list;
            for(int i = 0; i < 9; i++)
                node = node.next;
            System.out.println(revomeNode(node));
            print(list);
        }
    }
    
    class List {
        int data;
        List next;
    
        public List(int d) {
            this.data = d;
            this.next = null;
        }
    }
  • 相关阅读:
    mac 电脑自动登录服务器
    prometheus-operator 监控 k8s 外部集群
    生产prometheus-operator 监控二进制kubernetes
    微信小程序-nginx-https 代理后端服务
    Redis 高可用之哨兵模式
    Redis 高可用之数据持久化
    服务之间连接不上问题分析
    prometheus 告警指标
    错误代码:0x800706BE 解决方法
    泛微OA服务器更改IP地址后EMobile出现“调用远端服务器接口时发生错误(122)”的提示
  • 原文地址:https://www.cnblogs.com/giraffe/p/3210278.html
Copyright © 2020-2023  润新知