30+链表问题:概览

引子

昨天晚上,无意中刷到一篇关于链表的问题。突然又想起当年校招时被问到的一道有关链表面试题。突然心血来潮,准备记录一下,自己碰到的、或者搜罗到的一系列有关链表的面试题,在这里记录下来,并分享给大家。

文章目录

30+链表问题(一):如何判断链表是否成环?

30+链表问题(二):如何在一次循环中找到单链表的中间节点?

未完待续。。。

公共源码

在这里,我将贴出一些公共的源码,在后文中,我就不单独写了。

结点的实现:

/**
 * @author Zereao
 * @version 2019/9/6 11:45
 */
@Data
public class Node {
    /**
     * 指向前一个节点的引用
     */
    private Node pre;
    /**
     * 指向下一个节点的引用
     */
    private Node next;
    /**
     * 值
     */
    private String value;

    public Node(String value) {
        this.value = value;
    }
}

单链表实现:

/**
 * 一个 单链表的实现
 *
 * @author Zereao
 * @version 2019/9/6 11:47
 */
public class LinkedList {
    /**
     * 头指针
     */
    private Node head;
    /**
     * 尾指针
     */
    private Node tail;

    public void add(Node node) {
        if (this.tail == null) {
            this.head = node;
        } else {
            this.tail.setNext(node);
        }
        this.tail = node;
    }

    /**
     * 获取头结点
     *
     * @return 头结点
     */
    public Node getHead() {
        return this.head;
    }

    @Override
    public String toString() {
        if (this.head == null) {
            return null;
        }
        Node pointer = this.head;
        Node beforeTail = null;
        StringBuilder sb = new StringBuilder().append(pointer.getValue());
        while (pointer.getNext() != null) {
            Node next = pointer.getNext();
            if (next == tail) {
                if (beforeTail == null) {
                    beforeTail = pointer;
                    sb.append(" --> ").append(next.getValue());
                } else {
                    sb.append(" -----> ").append(next.getValue());
                    break;
                }
            } else {
                sb.append(" --> ").append(next.getValue());
            }
            pointer = next;
        }
        return sb.toString();
    }
}

源码附件

GitHub:https://github.com/Zereao/LinkListInterviewQuestion

参考文章

1、https://dzone.com/articles/20-linked-list-interview-questions-for-java-progra

2、https://javarevisited.blogspot.com/2017/07/top-10-linked-list-coding-questions-and.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值