数据结构与算法(二)单链表

过去的,未来的
2020-07-13 / 0 评论 / 0 点赞 / 584 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-07-13,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

一、简单介绍

单链表是链表的其中一种基本结构。一个最简单的结点结构如图所示,它是构成单链表的基本结点结构。在结点中数据域用来存储数据元素,指针域用于指向下一个具有相同结构的结点。
因为只有一个指针结点,称为单链表。

image.png

二、代码简单实现

1、节点对象
/**
 * 链表节点
 */
class Node{

    /**
     * 编号  不可重复
     */
    private int no;
    private String name;
    /**
     * 下一个节点
     */
    private Node next;
    public void setNext(Node next) {
        this.next = next;
    }
    public Node getNext() {
        return next;
    }


    public int getNo() {
        return no;
    }

    public Node(int no, String name){
        this.name=name;
        this.no=no;
    }

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

2、单链表的实现
/**
 * 单链表
 */
public class SinglelinkedList {

    /**
     * 头节点
     */
    private Node headNode=new Node(0,"");

    /**
     * 增加节点
     * @param node
     */
    public void add(Node node){
        if (node == null){
            throw new RuntimeException("参数不能为空");
        }
        Node temp=headNode;
        while (temp.getNext()!=null){
            if (temp.getNext().getNo() == node.getNo()){
                throw new RuntimeException("编号不可重复");
            }
            temp=temp.getNext();
        }
        temp.setNext(node);
    }

    /**
     * 根据编号删除节点
     * @param no
     */
    public void delete(int no){
        if (no <=0){
            throw new RuntimeException("参数不正确");
        }
        if (headNode.getNext() == null){
            throw new RuntimeException("单链表为空。。。");
        }
        Node temp=headNode;
        boolean flag=false;
        while (true){
            if (temp.getNext()== null){
                break;
            }
            if (temp.getNext().getNo() == no){
                flag=true;
                break;
            }
            temp=temp.getNext();
        }
        if (flag){
            temp.setNext(temp.getNext().getNext());
        }else {
            System.out.printf("编号为%d的节点没有找到\n",no);
        }
    }



    /**
     * 显示单链表的数据
     */
    public void show(){
        if (headNode.getNext() == null){
            throw new RuntimeException("单链表为空。。。");
        }
        Node temp=headNode;
        while (temp.getNext()!=null){
            System.out.println(temp.getNext());
            temp=temp.getNext();
        }
    }





    public static void main(String[] args) {

        SinglelinkedList singlelinkedList=new SinglelinkedList();
        singlelinkedList.add(new Node(1,"a"));
        singlelinkedList.add(new Node(2,"b"));
        singlelinkedList.add(new Node(3,"c"));
        singlelinkedList.show();
        System.out.println("******");
        singlelinkedList.delete(2);
        singlelinkedList.show();

        System.out.println("******");
        

    }


}
0

评论区