数据结构(五)——链表

前言

  上篇文章我们给大家介绍了队列,主要包括稀疏数组的含义以及相关二者之间的转换思路和及其实现,之后又介绍了队列的基本思想和用数组来模拟队列将其进行实现,通过模拟发现其存在的问题,然后再此基础上用数组模拟环形队列,有效的解决了各种队列存在的问题。今天,我们给大家介绍的是链表,主要是链表的介绍,链表的实现思路及其用java代码实现,接下来介绍双循环链表的相关内容,由于此部分内容是最重要的,在数据结构中是很关键的一环,因此,在讲解知识点的同时会穿插通过一些大公司的面试真题来让大家更好的理解其内容。首先介绍链表的基本知识。

一、链表介绍

  链表是指有序的列表,其实这里的链表更类似于C语言中的指针。具体在内存中的存储是如下的:

  由上图中可知,我们在链表中有以下的特点:

  1、链表是以节点的方式来存储,是链式存储
  2、每个节点包含data域,next域:指向下一个节点
  3、链表的每个节点不一定是连续存储
  4、链表分带头结点的链表和没有头结点的链表,根据实际需求来确定

  单链表(带头结点)逻辑结构如下图所示:

二、单链表实现

  我们接下来用带头结点的单向链表实现水浒传里排行榜的管理完成对英雄的增删改查的操作。这里需要注意的是:删除与修改,查找可以考虑学员独立完成,也可带学员完成。

  • 1、在添加英雄的时候,直接添加到链表的尾部,具体的实现思路分析如下:

   1、先创建一个head头结点,作用就是表示单链表的头
   2、后面我们每添加一个节点,就直接加入到链表的最后遍历,当然我们通过一个辅助变量遍历来帮助遍历整个链表。

  • 2、再添加英雄的时候,根据排名将英雄插入到指定位置。这里需要注意的是:如果有这个排名,则添加失败,并给出相应的提示。 具体的思路分析示意图入下:

   1、首先找到新添加的节点的位置,是通过辅助变量(指针),通过遍历来搞定
   2、新的节点temp.next = 新的节点
   3、将temp.next = 新的节点

  • 3、修改新的节点,具体的实现思路如下:

   1、先找到该节点,通过遍历
   2、 temp.name = newHeroNode.name;
  3、temp.nickname = new HeroNode.nickname;

  • 4、 删除节点,具体的思路如下图所示:

   从单链表中删除一个节点的思路:
  1、我们先找到需要删除的这个节点的前一个节点temp
  2、temp.next = temp.next.next;
  3、被删除的节点,将不会有其他引用的指向,会被垃圾回收机制回收

  • 5、完整的代码实现:
public class SingleLinkedListDemo {
    
    
    public static void main(String[] args) {
    
    
        // 创建节点
        HeroNode hero1 =  new HeroNode (1, "stefan", "shh");
        HeroNode hero2 =  new HeroNode (2, "napoleon", "nhh");
        HeroNode hero3 =  new HeroNode (3, "oliver", "ohh");
        HeroNode hero4 =  new HeroNode (1, "steve", "sth");
        // 创建链表
        SingleLinkedList singleLinkedList = new SingleLinkedList ();
        // 加入
//        singleLinkedList.add (hero1);
//        singleLinkedList.add (hero2);
//        singleLinkedList.add (hero3);
//        singleLinkedList.add (hero4);

        singleLinkedList.addByOrder (hero1);
        singleLinkedList.addByOrder (hero4);
        singleLinkedList.addByOrder (hero2);
        singleLinkedList.addByOrder (hero3);
        singleLinkedList.addByOrder (hero3);
        singleLinkedList.list ();
        HeroNode newHeroNode = new HeroNode (2, "nopoleon", "npp");
        singleLinkedList.update (newHeroNode);
        // 显示
//        singleLinkedList.list ();
        singleLinkedList.del (2);
        System.out.println ("=======");
        singleLinkedList.list ();
        // 测试代码
        System.out.println (getLength (singleLinkedList.getHead ()));
        HeroNode res = findLastIndexNode (singleLinkedList.getHead (), 1);
        System.out.println (res);
    }
    // 查找单链表的倒数第k个结点
    public static HeroNode findLastIndexNode(HeroNode head, int index){
    
    
        if(head.next == null){
    
    
            return null;
        }
        int size = getLength (head);
        if(index <= 0 || index > size){
    
    
            return null;
        }
        HeroNode cur = head.next;
        for(int i = 0; i < size - index; i++){
    
    
            cur = cur.next;
        }
        return cur;
    }

    //方法:获取到单链表的节点的个数(如果是带头结点的链表,需求不统计头结点)

    /**
     * 返回的就是有效节点的个数
     * @return
     */
    public static int getLength(HeroNode head){
    
    
        if(head.next == null){
    
    
            return 0;
        }
        int length = 0;
        // 定义一个辅助变量,这里我们没有统计头结点
        HeroNode cur = head.next;
        while (cur != null){
    
    
            length++;
            cur = cur.next;
        }
        return length;
    }
}

// 定义SingleLinkedList 管理我们的英雄
class SingleLinkedList{
    
    
    // 初始化头结点,头结点是固定的,不放任何数据
    private HeroNode head = new HeroNode (0, "", "");

    public HeroNode getHead(){
    
    
        return head;
    }
    // 添加方法
    // 思路:当不考虑编号的顺序时
    // 1、找到当前节点的最后节点
    // 2、将最后的节点的next域指向新的节点
    public void add(HeroNode heroNode){
    
    
        // 由于head节点是固定的,因此需要一个辅助指针
        HeroNode temp = head;
        // 遍历链表找到最后
        while (true){
    
    
            // 找到链表的最后
            if (temp.next == null){
    
    
                break;
            }
            // 如果没有找到,将temp后移
            temp = temp.next;
        }
        // 当循环退出while时,temp就指向了新的节点
        temp.next = heroNode;
    }

    /**
     * 第二种方法在添加英雄时,根据排名将英雄插入到指定位置
     * (如果有这个排名,则添加失败,并给出提示)
     */
    public void addByOrder(HeroNode heroNode){
    
    
        // 由于头结点是固定的;我们需要通过一个辅助制作(变量)来找到添加的位置
        // 因为单链表,因此,我们temp是位于添加的前一个节点,否则无法插入
        HeroNode temp = head;
        boolean flag = false; // 添加编号是否存在,默认为false
        while (true){
    
    
            if (temp.next == null){
    
    
                // temp在链表的最后
                break;
            }
            if (temp.next.no > heroNode.no){
    
    
                // 位置在于temp后面插入
                break;
            }
            else if (temp.next.no == heroNode.no){
    
    
                // 说明希望添加的heronode的编号存在
                flag = true;
                break;
            }
            temp = temp.next;
        }
        // 判断flag的值
        if(flag == true){
    
    
            System.out.printf ("准备插入的英雄的编号 %d 已经存在,不能加入\n" ,heroNode.no);
        }else {
    
    
            heroNode.next = temp.next;
            temp.next = heroNode;
        }
    }

    // 修改节点的信息,根据no编号来修改,即no编号不可改
    // 1、根据newNode的no来修改
    public void  update(HeroNode newHeroNode){
    
    
        // 判断是否为空
        if(head.next == null){
    
    
            System.out.println ("链表为空");
            return;
        }
        // 找到需要修改的节点,根据no编号
        // 定义一个辅助变量
        HeroNode temp = head.next;
        boolean flag = false; // 表示是否找到该节点
        while (true){
    
    
            if(temp == null){
    
    
                break; // 到链表的最后
            }
            if(temp.no == newHeroNode.no){
    
    
                flag = true;
                break;
            }
            temp = temp.next;
        }
        // 根据flag,是否找到要修改的节点
        if(flag){
    
    
            temp.name = newHeroNode.name;
            temp.nickname = newHeroNode.nickname;
        }else{
    
    
            // 没有找到
            System.out.printf ("没有找到编号为 %d 的节点,不能修改\n", newHeroNode.no);
        }
    }
    // 删除节点
    // 思路:
    // 1、head固定,我们仍然需要一个temp辅助找到待删除节点的前一个节点
    // 2、说明我们在比较的时候,是temp.next.no 和 需要删除的节点的no比较
    public void del(int no){
    
    
        HeroNode temp = head;
        boolean flag = false;
        while (true){
    
    
            if(temp.next == null){
    
    
                break;
            }
            if (temp.next.no == no){
    
    
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag){
    
    
            temp.next = temp.next.next;
        }else {
    
    
            System.out.printf ("要删除的 %d 节点不存在\n", no);
        }
    }


    // 显示链表
    public void list(){
    
    
        // 判断链表是否为空
        if(head.next == null){
    
    
            System.out.println ("链表为空");
            return;
        }
        // 由于头结点固定,需要一个辅助变量来遍历
        HeroNode temp = head.next;
        while (true){
    
    
            // 判断是否为链表最后
            if (temp == null){
    
    
                break;
            }
            // 输出结点信息
            System.out.println (temp);
            // 将next后移
            temp = temp.next;
        }

    }
}
// 定义heronode,每个heronode对象就是一个节点
class HeroNode{
    
    
    public int no;
    public String name;
    public String nickname;
    public HeroNode next; // 指向下一个节点
    // 构造器
    public HeroNode(int hNo, String hname, String hNickname){
    
    
        this.no = hNo;
        this.name = hname;
        this.nickname = hNickname;
    }
    // 为了显示方法,我们重新toString

    @Override
    public String toString() {
    
    
        return "HeroNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickname='" + nickname + '\'' +
                '}';
    }
}

  具体执行的效果如下图所示:

三、单链表的面试真题

  接下来我们给大家介绍著名的大公司面试题来帮助大家更好的理解单链表的相关知识及其实现,主要以新浪、百度、腾讯为主。

1、求单链表的中有效节点的个数

  我们可以用带头结点的链表,我们最后做统计的时候,把头结点去掉即可;具体的核心代码实现如下:

public class singleCount {
    
    
    public static int getLength(HeroNode head){
    
    
        if(head.next == null){
    
    // 空链表
            return  0;
        }
        int length = 0;
        // 定义一个辅助变量,这里我们没有统计头结点
        HeroNode cur = head.next;
        while (cur != null){
    
    
            length ++;
            cur = cur.next; // 遍历
        }
        return length;
    }
}

2、查找单链表中的倒数第k个结点

  其实我们在前面剑指offer中刷到此题,可以详细的查看链表中倒数第k个结点,这里有更加详细的介绍,但是为了本文的完整性,这里只写一种实现的思路与方法。我们分析题意可以有以下的思路:

   1、编写一个方法,接收head节点,同时接收一个index
   2、index表示是倒数第index个节点
   3、先把链表从头到尾遍历,得到链表的总长度getLength
   4、得到size后,我们从链表的第一个开始遍历(size-index)个,就可以得到
  5、如果找到了,则返回该节点,否则返回null

  具体的实现如下:

 public static HeroNode findLastIndexNode(HeroNode head, int index){
    
    
        // 判断如果链表为空,返回null
        if(head.next == null){
    
    
            return null; // 没有找到
        }
        // 第一个遍历得到的链表长度(节点个数)
        int size = getLength (head);
        // 第二次遍历size-index位置,就是我们倒数的第K个节点
        // 先做一个index校验
        if(index <= 0 || index > size){
    
    
            return null;
        }
        // 定义给辅助变量,for循环定位到倒数的index
        HeroNode cur = head.next; //3 3-1 = 2
        for (int i = 0 ; i < size - index; i++){
    
    
            cur = cur.next;
        }
        return cur;
    }

3、单链表的反转

  这道题与前道题一样,我们在前面的文章介绍过,这里有更加详细的介绍,但是为了本文的完整性,这里只写一种实现的思路与方法。我们分析题意可以有以下的思路:

  1、先定义一个节点reverseHead = new HeroNode();
  2、从头到尾遍历原来的链表,每遍历一个节点,就将其取出,并放在新的链表reverseHead的最前端
  3、原来的链表的head.next = reverseHrad.next;

  具体的代码如下:

public static void reversetList(HeroNode head){
    
    
        if(head.next == null || head.next.next == null){
    
    
            return;
        }
        HeroNode cur = head.next;
        HeroNode next = null;
        HeroNode reverseHead = new HeroNode (0, "", "");
        while (cur != null){
    
    
            next = cur.next;
            cur.next = reverseHead.next;
            reverseHead.next = cur;
            cur = next;
        }
        head.next = reverseHead.next;
    }

4、从尾到头打印单链表

  其实我们在前面剑指offer中刷到此题,可以详细的查看此文章,这里有更加详细的介绍,但是为了本文的完整性,这里只写一种实现的思路与方法。我们分析题意可以有以下的思路:

  1、上面的题的要求逆序打印单链表
  2、方式1:先将单链表进行反转操作,然后再遍历即可,这样的做的问题是会破坏原来的单链表的结构
  3、方式2:可以利用栈这个数据结构,将各个节点压入到栈中,然后利用栈的先进后出的特点,就实现了逆序打印的效果。

  具体的实现如下:

public static void reversePrint(HeroNode head){
    
    
        if(head.next == null){
    
    
            return;
        }
        Stack<HeroNode> stack = new Stack<HeroNode> ();
        HeroNode cur = head.next;
        while (cur != null){
    
    
            stack.push (cur);
            cur = cur.next;
        }
        while (stack.size () > 0){
    
    
            System.out.println (stack.pop ());
        }
    }

四、双向链表

  使用带head头的双向链表实现,我们还是以前面的案例为操作对象。管理单向链表的缺点分析:

  1、单向链表,查找的方向只能是一个方向,而双向链表可以向前或者向后查找
  2、单向链表不能自我删除,需要靠辅助接点,而双向链表,则可以自我删除,所以前面我们单链表删除时节点,总是能找到temp,temp是待删除节点的前一个节点
  3、分析了双向链表如何完成遍历、添加、修改和删除的思路

  1、遍历和单链表一样,只是可以向前,也可以向后查找
  2、先找到双向链表的最后这个节点
  temp.next = newHeroNode;
  newHeroNode.pre = temp;
  修改和原来的单链表是一致的
  在删除的时候,由于是双向链表,因此,我们可以实现自我删除某个节点
  直接找到要删除节点
  temp.pre.next = temp.next;
  temp.next.pre = temp.pre;

  双向链表的实现

public class DoubleLinkedListDemo {
    
    
    //定义HeroNode,每个HeroNode对象就是一个节点
    static class HeroNode{
    
    

        public int no;
        public String name;
        public String nickname;
        public HeroNode next; //指向下一个节点
        public HeroNode pre; //指向前一个节点

        //构造器
        public HeroNode(int no,String name,String nickname) {
    
    
            this.no = no;
            this.name = name;
            this.nickname = nickname;

        }

        @Override
        public String toString() {
    
    
            return "HeroNode [no=" + no +",name="+ name +",nickname="+ nickname+"]";
        }


    }

    static class DoubleLinkList{
    
    
        //先初始化一个头节点,头节点不动,不存放具体的数据
        private HeroNode head = new HeroNode(0,"","");

        public HeroNode getHead() {
    
    
            return head;
        }


        //显示链表(遍历)
        public void list() {
    
    

            //判断链表是否为空
            if(head.next == null) {
    
    
                System.out.println("链表为空");
                return;
            }
            //因为头节点不能动同上需要temp
            HeroNode temp = head.next;
            while(true) {
    
    
                if(temp == null) {
    
    
                    break;
                }
                System.out.println(temp);
                temp = temp.next;
            }
            //当退出循环的时候,temp只可能在链表的最后
            //将这个节点的next指向新的节点

        }

        public void add(HeroNode heroNode) {
    
    
            //因为头不能动,所以需要辅助遍历temp
            HeroNode temp = head;
            boolean flag = false;
            while(true) {
    
    
                if(temp.next == null) {
    
    
                    //说明找到了链表的最后
                    break;
                }
                if(temp.next.no > heroNode.no) {
    
    
                    break;
                }else if(temp.next.no == heroNode.no) {
    
    
                    flag = true;  //说明编号存在
                    break;
                }
                temp = temp.next;
            }
            if(flag) {
    
    
                System.out.printf("英雄编号%d已经存在了:\n " , heroNode.no);
            }else {
    
    
                //改进 需要有序插入
                //插入到链表中 在temp 和temp.next之间
                //目前已实现有序插入
                if(temp.next == null) {
    
    
                    temp.next = heroNode;
                    heroNode.pre = temp;
                }else {
    
    
                    heroNode.next = temp.next;

                    temp.next.pre = heroNode;
                    heroNode.pre = temp;
                    temp.next = heroNode;
                }
            }
            //当退出循环的时候,temp只可能在链表的最后
            //将这个节点的next指向新的节点

        }


        //删除节点
        public void delete(int no) {
    
    
            if(head.next == null) {
    
    
                System.out.println("链表是空的");
                return;
            }
            HeroNode temp = head.next;
            boolean flag = false;

            while(true) {
    
    
                if(temp.no == no) {
    
    
                    flag = true;
                    break;
                }if(temp.next == null){
    
    
                    break;
                }
                temp = temp.next;

            }
            if(flag) {
    
    
                temp.pre.next = temp.next;
                if(temp.next != null) {
    
    
                    //如果不是最后一个节点,执行这种情况,否则出现空指针异常
                    temp.next.pre = temp.pre;

                }else {
    
    
                    temp.pre.next = null;
                }
            }else {
    
    
                System.out.printf("编号为%d的HeroNode不存在",no);

            }
        }


        //修改节点内容
        public void update(HeroNode heroNode) {
    
    
            if(head.next == null) {
    
    
                System.out.println("链表为空");
                return;
            }
            HeroNode temp = head.next;
            boolean flag = false;
            while(true) {
    
    
                if(temp.next == null)
                    break;
                if(temp.no ==heroNode.no) {
    
    
                    flag = true;
                    break;
                }
                temp = temp.next;
            }
            if(flag) {
    
    
                temp.name = heroNode.name;
                temp.nickname = heroNode.nickname;
            }else
                System.out.printf("不存在编号为%d的HeroNode",heroNode.no);
        }


    }

    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        HeroNode hero1 = new HeroNode(1,"宋江","及时雨");
        HeroNode hero2 = new HeroNode(2,"卢俊义","玉麒麟");
        HeroNode hero3 = new HeroNode(3,"吴用","智多星");
        HeroNode hero4 = new HeroNode(4,"林冲","豹子头");


        //创建链表
        DoubleLinkList doublelinklist = new DoubleLinkList();
        doublelinklist.add(hero1);


        doublelinklist.add(hero4);
        doublelinklist.add(hero2);
        doublelinklist.add(hero3);

        doublelinklist.list();
        HeroNode hero = new HeroNode(2,"校长","兔子");

        doublelinklist.update(hero);
        doublelinklist.list();

        doublelinklist.delete(2);
        doublelinklist.list();
        doublelinklist.delete(4);
        doublelinklist.list();
    }
}

  具体的执行如下:

五、单向环形链表

  我们其实在前面的文章介绍过约瑟夫的问题,其实用到的就是单向的循环链表。具体的实现思路如下所示:

  具体单向循环链表的思路如下:

  1、先创建第一个节点,让first指向该项节点,并形成环形
  2、后面当我们每创建一个新的节点,就把该节点,加入到已有的环形链表中即可
  3、先让一个辅助指针(变量)curBoy,指向first节点
  4、然后通过一个while循环遍历该环形链表即可curBoy.next == first结束

  约瑟夫的思路分析如图所示:

  具体的代码实现

class Boy {
    
    
    private int no;
    private Boy next;//指向下一个节点 默认null

    public Boy(int no) {
    
    
        this.no = no;
    }

    public int getNo() {
    
    
        return no;
    }

    public void setNo(int no) {
    
    
        this.no = no;
    }

    public Boy getNext() {
    
    
        return next;
    }

    public void setNext(Boy next) {
    
    
        this.next = next;
    }
}
public class CircleSingleLinkedList {
    
    
    //创建一个first节点 当前没有编号 代表第一个小孩
    private Boy first = new Boy(-1);

    //添加小孩节点,构建成一个环形的链表
    public void addBoy(int nums) {
    
    //nums代表总的小孩个数
        if (nums < 1) {
    
    
            System.out.printf("nums值不正确");
            return;
        }
        //因为first不能动  所以创建一个辅助指针来构建环形链表
        Boy curBoy = null;
        for (int i = 1; i <=nums; i++) {
    
    
            //根据编号创建小孩节点
            Boy boy = new Boy(i);
            //第一个小孩 自己构成环形
            if (i == 1) {
    
    
                first = boy;
                boy.setNext(first);
                curBoy = first;
            } else {
    
    
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy = boy;
            }
        }

    }

    //显示环形链表
    public void showBoy() {
    
    
        if (first == null) {
    
    
            System.out.println("链表为空,无小孩");
            return;
        }
        //因为first不能动 仍然需要辅助指针
        Boy curBoy = first;
        while (true) {
    
    
            System.out.printf("小孩的编号是:%d\n", curBoy.getNo());
            if (curBoy.getNext() == first) {
    
    
                break;
            }
            curBoy = curBoy.getNext();//curBoy后移
        }
    }

    //根据用户的输入计算出小孩出圈的顺序

    /**
     * @param startNo  表示从第几个小孩开始数数
     * @param countNum 表示数几下
     * @param nums     表示最初有多少小孩
     */
    public void countBoy(int startNo, int countNum, int nums) {
    
    
        if (first == null || startNo < 1 || startNo > nums) {
    
    
            System.out.printf("参数输入有误 请重新输入");
            return;
        }
        //创建辅助指针 帮助小孩出圈
        Boy helper = first;
        //辅助指针应该指向环形链表的最后节点
        while (true) {
    
    
            if (helper.getNext() == first) {
    
    
                break;//说明helper指向最后一个小孩节点
            }
            helper = helper.getNext();
        }
        //小孩报数前,先让first和helper移动k-1次
        for (int i = 0; i < startNo - 1; i++) {
    
    
            first = first.getNext();
            helper = helper.getNext();
        }
        //小孩报数时,让first和helper移动m-1次 然后出圈
        while (true) {
    
    
            if (helper == first) {
    
    
                break;//圈中只剩一个节点
            }
            for (int i = 0; i < countNum - 1; i++) {
    
    
                first = first.getNext();
                helper = helper.getNext();
            }
            //这时first指向的节点就是要出圈的小孩
            System.out.printf("小孩%d出圈\n", first.getNo());
            //将first指向的节点出圈
            first = first.getNext();
            helper.setNext(first);
        }
        System.out.printf("最后留在圈中的小孩编号%d\n", helper.getNo());
    }
}
class Josepfu {
    
    
    public static void main(String[] args) {
    
    
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        circleSingleLinkedList.showBoy();
        circleSingleLinkedList.countBoy(1,2,5);
    }
}

  执行的效果如下:

六、总结

  上篇文章给大家介绍了队列,主要包括稀疏数组的含义以及相关二者之间的转换思路和及其实现,之后又介绍了队列的基本思想和用数组来模拟队列将其进行实现,通过模拟发现其存在的问题,然后再此基础上用数组模拟环形队列,有效的解决了各种队列存在的问题。本文给大家介绍的是链表,主要包括链表的介绍,链表的实现思路及其用java代码实现,另外还介绍双循环链表的相关内容,由于此部分内容是最重要的,在数据结构中是很关键的一环,因此,在讲解知识点的同时还穿插通过一些大公司的面试真题来让大家更好的理解其内容。其实数据结构与算法是特别重要的,在编程中有至关重要的地位,因此,需要我们特别的掌握。生命不息,奋斗不止,我们每天努力,好好学习,不断提高自己的能力,相信自己一定会学有所获。加油!!!

猜你喜欢

转载自blog.csdn.net/Oliverfly1/article/details/112462216