链表LinkedList(不带头结点)代码实现

 

头结点一般称为head。其数据域不存储数据,指针域指向第一个数据域有内容的结点(一般把该结点称为第一个结点)。

/**
 * @author admin
 * @version 1.0.0
 * @ClassName LoopNode.java
 * @Description TODO
 * @createTime 2021年08月15日 09:31:00
 */
public class NodeTest {
    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));
        node1.show();
        node2.show();
        node2.insert(new Node(5));
        node1.show();

        //System.out.println(node1.next);//返回的是地址值Node@1b6d3586
        // System.out.println(node1.getNext());//返回的是地址值Node@1b6d3586
        //System.out.println(node1.next.data);//返回的是结点1的下一个结点存储的数据
        //System.out.println(node1.next.next.data);//返回1 2 3 4

    }
}


public  class Node {
    int data;//存储的数据
    Node next;

    //构造器,创对象时同时赋值
    Node(int num){
        this.data=num;
    }
    //添加结点
    public Node append(Node node){
        Node currentnode =this;
        while (true){
            Node nextNode =currentnode.next;
            if (nextNode==null)//currentnode后面再无结点,即currentnode是最后一个结点。
                break;
            currentnode=nextNode;
        }
        currentnode.next=node;
        return this;//返回添加的结点。
    }

    //返回该结点下一个结点
    public Node getNext(){
        return this.next;
    }

    //返回该结点存储的数据。
    public int getData(){
        return this.data;
    }

    //展示结点
    public void show(){
        Node currentnode=this;
        while (true){
            System.out.print(currentnode.data+" ");
            currentnode=currentnode.next;
            if(currentnode==null)
                break;
        }
        System.out.println();
    }

    //删除结点
    public void removenext(){
        Node newnext=next.next;
        this.next=newnext;
    }


    //插入结点
    public void insert (Node node){
        Node nextnext=this.next;
        this.next=node;
        node.next=nextnext;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值