数据结构代码实现 —— 单链表【Java】

单链表的概述及性质等在篇不做赘述,有需要可移步以下文章:

《数据结构 C语言版 严蔚敏 第2版》:线性表icon-default.png?t=N7T8https://blog.csdn.net/weixin_43551213/article/details/134048025 

以下仅展示使用 Java 实现单链表

 

结点结构定义:

public class SingleLinkedList {
    private int data;
    private SingleLinkedList next;
}

数据结构代码实现 —— 单链表【Java】_第1张图片 

追加元素:

public SingleLinkedList append(SingleLinkedList node){
    SingleLinkedList nowNode = this;
    while (true){
        SingleLinkedList nextNode = nowNode.next;
        if(null == nextNode){
            break;
        }
        nowNode = nextNode;
    }
    nowNode.next = node;
    return this;
}

数据结构代码实现 —— 单链表【Java】_第2张图片

 

删除元素:

public void deleteNext(){
    this.next = this.next().next();
}

数据结构代码实现 —— 单链表【Java】_第3张图片 

插入元素:

public void insertNode(SingleLinkedList node){
    node.next = this.next();
    this.next = node;
}

数据结构代码实现 —— 单链表【Java】_第4张图片 

打印链表:

public String show(){
    SingleLinkedList tempNode = this;
    StringBuilder builder = new StringBuilder("[" + String.valueOf(tempNode.getData()));
    while (tempNode.next != null){
        tempNode = tempNode.next();
        builder.append(" ").append(String.valueOf(tempNode.getData()));
    }
    builder.append("]");
    return builder.toString();
}

 

测试程序:

/**
 * @Author: QiuXuan
 * @Email: [email protected]
 * @Project: DataStructure
 * @Date: 2024-01-19 16:27
 * @Version 1.0
 * @Since 1.0
 **/
public class SingleLinkedListTest {
    public static void main(String[] args){
        SingleLinkedList listNode = new SingleLinkedList(2);
        listNode.append(new SingleLinkedList(3));
        listNode.append(new SingleLinkedList(4));
        listNode.append(new SingleLinkedList(5)).append(new SingleLinkedList(6));
        System.out.print(listNode.getData() + " ");
        System.out.print(listNode.next().getData() + " ");
        System.out.print(listNode.next().next().getData() + " ");
        System.out.print(listNode.next().next().next().getData() + " ");
        System.out.println(listNode.next().next().next().next().getData() + " ");

        listNode.deleteNext();
        System.out.println(listNode.show());

        listNode.insertNode(new SingleLinkedList(7));
        System.out.println(listNode.show());
    }
}

测试程序与上文画的图使用的数据不是一致的!!! 

一  叶  知  秋,奥  妙  玄  心 

你可能感兴趣的:(数据结构,数据结构,链表)