算法与数据结构之链表


链表(Linked List)介绍

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

单链表的应用实例

使用带 head 头的单向链表实现 –水浒英雄排行榜管理完成对英雄人物的增删改查操作, 注: 删除和修改,查找

  1. 第一种方法在添加英雄时,直接添加到链表的尾部

  2. ) 第二种方式在添加英雄时,根据排名将英雄插入到指定位置(如果有这个排名,则添加失败,并给出提示)

  3. 修改节点功能

    • 思路(1) 先找到该节点,通过遍历
    • (2) temp.name = newHeroNode.name ; temp.nickname= newHeroNode.nicknam
  4. 删除节点

代码演示

package com.atguigu.linkedlist;

import java.util.Stack;

public class SingleLinkedListDemo {

    public static void main(String[] args) {
        HeroNode hero1 = new HeroNode(1, "宋江", "及时雨");
        HeroNode hero2 = new HeroNode(2, "卢俊义", "玉麒麟");
        HeroNode hero3 = new HeroNode(3, "吴用", "智多星");
        HeroNode hero4 = new HeroNode(4, "林冲", "豹子头");
        SingleLinkedList singleLinkedList = new SingleLinkedList();
//        singleLinkedList.add(hero1);
//        singleLinkedList.add(hero2);
//        singleLinkedList.add(hero3);
//        singleLinkedList.add(hero4);
        singleLinkedList.addByOder(hero1);
        singleLinkedList.addByOder(hero4);
        singleLinkedList.addByOder(hero2);
        singleLinkedList.addByOder(hero3);
        singleLinkedList.list();
        //修改节点信息
        HeroNode newHeroNode = new HeroNode(2, "小鹿", "玉麒麟");
        singleLinkedList.update(newHeroNode);
        System.out.println("修改节点信息后");
        singleLinkedList.list();
        System.out.println("删除节点信息后");
        //singleLinkedList.del(1);
        //singleLinkedList.del(4);
        
        singleLinkedList.list();
        //获取单链表的有效节点个数(不统计头节点)
        System.out.println(getLength(singleLinkedList.getHead()));
        //查找单链表中的倒数第k个节点
        HeroNode res=findLastIndexNode(singleLinkedList.getHead(), 1);
        System.out.println("res="+res);
        //单链表的反转
        reversetList(singleLinkedList.getHead());
        singleLinkedList.list();
        //逆序打印单链表
        System.out.println("逆序打印单链表");
        reversePrint(singleLinkedList.getHead());
        
        
    }
//获取单链表的有效节点个数(不统计头节点)
    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;
    }
//查找单链表中的倒数第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;
    }
//单链表的反转    
    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;
    }
//逆序打印单链表
    public static void reversePrint(HeroNode head) {
        if (head.next==null) {
            return;
        }
        Stack<HeroNode> stack = new Stack<>();
        HeroNode cur=head.next;
        while (cur!=null) {
            stack.push(cur);
            cur=cur.next;
        }
        while (stack.size()>0) {
            System.out.println(stack.pop());
        }
    }
}
class SingleLinkedList{
    private HeroNode head=new HeroNode(0, "", "");
    //返回头节点
    public HeroNode getHead() {
        return head;
    }
    public void setHead(HeroNode head) {
        this.head = head;
    }
    
    
    
    public void add(HeroNode heroNode){
        HeroNode temp=head;
        while (true) {
            if (temp.next==null) {
                break;
            }
            temp=temp.next;
        }
        temp.next=heroNode;
    }
    public void addByOder(HeroNode heroNode) {
        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 {
            heroNode.next=temp.next;
            temp.next=heroNode;
        }
    }
    //修改节点的信息,根据no编号来修改
    public void update(HeroNode newHeroNode) {
        if (head.next==null) {
            System.out.println("链表为空");
            return;
        }
        HeroNode temp=head.next;
        boolean flag=false;
        while (true) {
            if (temp==null) {
                break;
            }
            if (temp.no==newHeroNode.no) {
                flag=true;
                break;
            }
            temp=temp.next;
        }
        if (flag) {
            temp.name=newHeroNode.name;
            temp.nickname=newHeroNode.nickname;
        }else {
            System.out.printf("没有找到编号%d的节点,不能修改\n",newHeroNode.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);
            temp=temp.next;
        }
    }
}
class HeroNode{
    public int no;
    public String name;
    public String nickname;
    public HeroNode next;
    public HeroNode(int no, String name, String nickname) {
        super();
        this.no = no;
        this.name = name;
        this.nickname = nickname;
    }
    @Override
    public String toString() {
        return "HeroNode [no=" + no + ", name=" + name + ", nickname=" + nickname  + "]";
    }
}

单链表面试题(新浪、百度、腾讯)

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

    //方法:获取到单链表的节点的个数(如果是带头结点的链表,需求不统计头节点)
    /**
    *
    * @param head 链表的头节点
    * @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;
    }
    
  2. 查找单链表中的倒数第 k 个结点 【新浪面试题】

    //查找单链表中的倒数第 k 个结点 【新浪面试题】
    //思路
    //1. 编写一个方法,接收 head 节点,同时接收一个 index
    //2. index 表示是倒数第 index 个节点
    //3. 先把链表从头到尾遍历,得到链表的总的长度 getLength
    //4. 得到 size 后,我们从链表的第一个开始遍历 (size-index)个,就可以得到
    //5. 如果找到了,则返回该节点,否则返回 nulll
    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;
    }
    
    1. 单链表的反转【腾讯面试题,有点难度】

      //将单链表反转
      public static void reversetList(HeroNode head) {
      //如果当前链表为空,或者只有一个节点,无需反转,直接返回
      if(head.next == null || head.next.next == null) {
      return ;
      }
      //定义一个辅助的指针(变量),帮助我们遍历原来的链表
      HeroNode cur = head.next;
      HeroNode next = null;// 指向当前节点[cur]的下一个节点
      HeroNode reverseHead = new HeroNode(0, "", "");
      //遍历原来的链表,每遍历一个节点,就将其取出,并放在新的链表 reverseHead 的最前端
      //动脑筋
      while(cur != null) {
      next = cur.next;//先暂时保存当前节点的下一个节点,因为后面需要使用
      cur.next = reverseHead.next;//将 cur 的下一个节点指向新的链表的最前端
      reverseHead.next = cur; //将 cur 连接到新的链表上
      cur = next;//让 cur 后移
      }
      //将 head.next 指向 reverseHead.next , 实现单链表的反转
      head.next = reverseHead.next;
      }
      
      1. 从尾到头打印单链表 【百度,要求方式 1:反向遍历 。 方式 2:Stack 栈

        //单链表的逆序打印代码
        //可以利用栈这个数据结构,将各个节点压入到栈中,然后利用栈的先进后出的特点,就实现了逆序打印的效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; //cur 后移,这样就可以压入下一个节点
        }
        //将栈中的节点进行打印,pop 出栈
        while (stack.size() > 0) {
        System.out.println(stack.pop()); //stack 的特点是先进后出
        }
        }
        

双向链表应用实例

双向链表的操作分析和实现

  1. 管理单向链表的缺点分析:

    • 单向链表,查找的方向只能是一个方向,而双向链表可以向前或者向后查找。

    • 单向链表不能自我删除,需要靠辅助节点 ,而双向链表,则可以自我删除,所以前面我们单链表删除 时节点,总是找到 temp,temp 是待删除节点的前一个节点.

    • 分析了双向链表如何完成遍历,添加,修改和删除的思路

  2. 分析 双向链表的遍历,添加,修改,删除的操作思路===》代码实现

    • 遍历 方和 单链表一样,只是可以向前,也可以向后查找

      添加 (默认添加到双向链表的最后)

      • 先找到双向链表的最后这个节点
      • temp.next = newHeroNod
      • newHeroNode.pre = temp
    • 修改 思路和 原来的单向链表一样

    • 删除

      • 因为是双向链表,因此,我们可以实现自我删除某个节点
      • 直接找到要删除的这个节点,比如 temp
      • temp.pre.next
      • temp.next.pre = temp.pre;

双向链表的代码实现

package com.atguigu.linkedlist;

public class DoubleLinkedListDemo {

    public static void main(String[] args) {
        HeroNode2 hero1 = new HeroNode2(1, "宋江", "及时雨");
        HeroNode2 hero2 = new HeroNode2(2, "卢俊义", "玉麒麟");
        HeroNode2 hero3 = new HeroNode2(3, "吴用", "智多星");
        HeroNode2 hero4 = new HeroNode2(4, "林冲", "豹子头");
        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
        doubleLinkedList.add(hero1);
        doubleLinkedList.add(hero2);
        doubleLinkedList.add(hero3);
        doubleLinkedList.add(hero4);
        doubleLinkedList.list();
        //修改信息
        HeroNode2 newHeroNode = new HeroNode2(4, "公孙胜", "入云龙");
        doubleLinkedList.update(newHeroNode);
        System.out.println("修改后的双链表");
        doubleLinkedList.list();
        //删除
        System.out.println("删除后的双链表");
        doubleLinkedList.del(3);
        doubleLinkedList.list();
    }

}
class DoubleLinkedList{
    private HeroNode2 head=new HeroNode2(0, "", "");
    //返回头节点
    public HeroNode2 getHead() {
        return head;
    }
    public void add(HeroNode2 heroNode){
        HeroNode2 temp=head;
        while (true) {
            if (temp.next==null) {
                break;
            }
            temp=temp.next;
        }
        temp.next=heroNode;
        heroNode.pre=temp;
    }
    public void update(HeroNode2 newHeroNode) {
        if (head.next==null) {
            System.out.println("链表为空");
            return;
        }
        HeroNode2 temp=head.next;
        boolean flag=false;
        while (true) {
            if (temp==null) {
                break;
            }
            if (temp.no==newHeroNode.no) {
                flag=true;
                break;
            }
            temp=temp.next;
        }
        if (flag) {
            temp.name=newHeroNode.name;
            temp.nickname=newHeroNode.nickname;
        }else {
            System.out.printf("没有找到编号%d的节点,不能修改\n",newHeroNode.no);
        }
    }
    public void del(int no) {
        if (head.next==null) {
            System.out.println("链表为空,无法删除");
            return;
        }
        HeroNode2 temp=head.next;
        boolean flag=false;
        while (true) {
            if (temp==null) {
                break;
            }
            if (temp.no==no) {
                flag=true;
                break;
            }
            temp=temp.next;
        }
        if (flag) {
            //temp.next=temp.next.next;
            temp.pre.next=temp.next;
            if (temp.next!=null) {
                
                temp.next.pre=temp.pre;
            }
        }else {
            System.out.printf("要删除的%d结点不存在\n",no);
        }
    }
    
    
    public void list() {
        if (head.next==null) {
            System.out.println("链表为空");
            return;
        }
        HeroNode2 temp=head.next;
        while (true) {
            if (temp==null) {
                break;
            }
            System.out.println(temp);
            temp=temp.next;
        }
    }
}
class HeroNode2{
    public int no;
    public String name;
    public String nickname;
    public HeroNode2 next;
    public HeroNode2 pre;
    public HeroNode2(int no, String name, String nickname) {
        super();
        this.no = no;
        this.name = name;
        this.nickname = nickname;
    }
    @Override
    public String toString() {
        return "HeroNode2 [no=" + no + ", name=" + name + ", nickname=" + nickname  + "]";
    }
}

单向环形链表应用场景

  • Josephu(约瑟夫、约瑟夫环) 问题

    Josephu 问题为:设编号为 1,2,… n 的 n 个人围坐一圈,约定编号为 k(1<=k<=n)的人从 1 开始报数,数 到 m 的那个人出列,它的下一位又从 1 开始报数,数到 m 的那个人又出列,依次类推,直到所有人出列为止,由 此产生一个出队编号的序列。

    提示:用一个不带头结点的循环链表来处理 Josephu 问题:先构成一个有 n 个结点的单循环链表,然后由 k 结 点起从 1 开始计数,计到 m 时,对应结点从链表中删除,然后再从被删除结点的下一个结点又从 1 开始计数,直 到最后一个结点从链表中删除算法结束。

  • 单向环形链表介绍之Josephu 问题

    Josephu 问题为:设编号为 1,2,… n 的 n 个人围坐一圈,约定编号为 k(1<=k<=n)的人从 1 开始报数,数到 m 的那个人出列,它的下一位又从 1 开始报数,数到 m 的那个人又出列,依次类推,直到所有人出列为止,由此 产生一个出队编号的序列。

  • 提示

    用一个不带头结点的循环链表来处理 Josephu 问题:先构成一个有 n 个结点的单循环链表,然后由 k 结点起从 1 开 始计数,计到 m 时,对应结点从链表中删除,然后再从被删除结点的下一个结点又从 1 开始计数,直到最后一个结点从链表中删除算法结束。

Josephu 问题的代码实现

package com.atguigu.linkedlist;
//环形单向链表
public class Josepfu {

    public static void main(String[] args) {
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        circleSingleLinkedList.showBoy();
        circleSingleLinkedList.countBoy(1, 2, 5);
    }

}
class CircleSingleLinkedList{
    private Boy first = null;
    //private Boy first=new Boy(-1);
    public void addBoy(int nums) {
        if (nums<1) {
            System.out.println("nums的值不正确");
            return;
        }
        Boy curBoy=null;
        for (int i = 1; i <= nums; i++) {
            Boy boy = new Boy(i);
            if (i==1) {//第一个小孩
                first=boy;
                first.setNext(first);
                curBoy=first;
            }else{
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy=boy;
            }
        }
    }
    public void showBoy() {
        if (first==null) {
            System.out.println("没有任何小孩(链表为空)");
            return;
        }
        
        Boy curBoy=first;
        while (true) {
            System.out.printf("小孩的编号%d\n",curBoy.getNo());
            if (curBoy.getNext()==first) {
                break;
            }
            curBoy=curBoy.getNext();
        }
        
    }
    //计算小孩出圈的顺序
    public void countBoy(int startNo,int countNum,int nums) {
        if (first==null || startNo<1 || startNo>nums) {
            System.out.println("参数输入有误,请重新输入");
            return;
        }
        Boy helper=first;
        while (true) {
            if (helper.getNext()==first) {
                break;
            }
            helper=helper.getNext();
        } 
        for (int i = 0; i <startNo-1; i++) {
            first=first.getNext();
            helper=helper.getNext();
        }
        while (true) {
            if (helper==first) {
                break;
            }
            for (int i = 0; i < countNum-1; i++) {
                first=first.getNext();
                helper=helper.getNext();
            }
            System.out.printf("小孩出圈%d\n",first.getNo());
            first=first.getNext();
            helper.setNext(first);
        }
        System.out.printf("最后留在圈里的小孩编号%d\n",first.getNo());
    }
}
class Boy{
    private int no;
    private Boy next;
    public Boy(int no) {
        super();
        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;
    }
    
}

文章作者: 读序
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 读序 !
  目录