java之单项非循环无头节点链表

class Node{
    public int data;
    public Node next;
    public Node(int data){
        this.data = data;
        this.next = null;      //  每次创建对象时,将node保存在对象里面
    }
}

public class LinkedList {
    public Node head;    // 保存单链表头结点的引用
    // 头插法
    public void addFirst(int data){
        Node node = new Node(data);
        if(this.head == null){
            // 第一次插入节点
            this.head = node;
            return;
        }
        node.next = this.head;
        this.head = node;
    }
    //   打印单链表
    public void display(){
        Node cur = this.head;
        while(cur != null){   //如果让cur.next != null,则最后一个数打印不出来
            System.out.print(cur.data + " ");
            cur = cur.next;
        }
        System.out.println("");
    }
    //  尾插法
    public void addLast(int data){
        Node node = new Node(data);
        if(this.head == null){
            this.head = node;
            return;
        }
        Node cur = this.head;
        while(cur.next != null){
            cur = cur.next;
        }
        cur.next = node;
    }
    //  查找是否包含关键字key在单链表中
    public boolean contains(int key){
        Node cur = this.head;
        while(cur != null){
            if(cur.data == key){
                return true;
            }
            cur = cur.next;
        }
        return false;
    }
    // 得到单链表的长度
    public int size(){
        int count = 0;
        Node cur = this.head;
        while(cur != null){
            count++;
            cur = cur.next;
        }
        return count;
    }
    // 在任意位置插入插入data
    public void addIndex(int index , int data) {
        if (index == 0) {
            this.addFirst(data);
            return;
        } else if (index == this.size()) {
            this.addLast(data);
            return;
        } else {
            Node node = new Node(data);
            Node cur = searchIndex(index);
            node.next = cur.next;
            cur.next = node;
        }
    }
    private Node searchIndex(int index){
        if(index < 0 || index > this.size()){
            throw new RuntimeException("index位置不合法");
        }
        Node cur = this.head;
        while(index - 1 != 0){
            cur = cur.next;
            index--;
        }
        return cur;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值