往单链表中插入节点

package TestTwo.demo1;

public class Node {
    //链表数据
    int data;
    //下一个节点
    Node next;
    //构造方法
    public Node(int data){
        this.data = data;
    }
    //给节点添加下(下)一个节点
    public Node append(Node node) {
        Node currentNode = this;
        while (true) {
            if (currentNode.next == null) {
                break;
            }
            currentNode = currentNode.next;
        }
        currentNode.next = node;
        return currentNode.next;
    }

    //判断当前节点是否为最后一个节点
    public boolean isLast(){
        return this.next==null;
    }

    //取得当前节点的数据
    public int getData() {
        return data;
    }

    //获取当前节点的下下一个节点
    public void deleteNode(){
        if (this.next==null){
//            throw new NullPointerException("Null Pointer!");
            System.out.println("Null Pointer!");
        }else {
            this.next = this.next.next;
        }
    }
    //取得当前节点的下一个节点
    public Node getNext() {
        return next;
    }
    public void show(){
        Node currentNode = this;
        while (true){
            System.out.println(currentNode.getData()+" ");
            currentNode = currentNode.next;
            if (currentNode==null){
                break;
            }
        }
        System.out.println();
    }
    //往单链表中插入节点
    public void insert(Node node2){

        if (this.next != null) {
            node2.next = this.next;
        }
        this.next = node2;
    }
}

package TestTwo.demo1.test;

import TestTwo.demo1.Node;

public class TestNode {
    public static void main(String[] args) {
        //创造三个节点
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        //将这三个节点关联上,并创建和添加第四个节点
        node1.append(node2).append(node3).append(new Node(4));
        //显示第三个节点是否为最后一个节点
        System.out.println(node1.getNext().getNext().isLast());
        //显示第四个节点的数据
        System.out.println(node1.getNext().getNext().getNext().getData());
        node3.deleteNode();
        System.out.println(node1.getNext().getNext().isLast());
        node3.deleteNode();
        node1.show();
        node3.insert(new Node(5));
        node3.show();
    }
}

发布了55 篇原创文章 · 获赞 15 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_43141611/article/details/105196838