20241027--数据结构--链表

文章目录

利用给Java实现链表数据结构。
首先整体这个类就是一个链表,链表里面有头节点,尾节点,链表大小,如何表示节点呢,就在这个链表类里面定义一个成员内部类,节点有前节点,后节点,节点元素。

将元素插入链表尾部,把tail赋值给一个变量l,构建一个节点,这个节点前节点是 l,后节点为null,元素就是传进来的 。
将这个新构建的节点 赋值给tail,将原来的tail的后节点赋值给现在的tail。

package com.kong.demo1;
import java.util.NoSuchElementException;

/**
 * @author kongdeming
 * @date 2024/10/28
 **/
/*-----这个类整体是链表-------*/
public class LinkList<E> {

    /*------定义节点结构-------*/
    public class Node<E>{
        Node<E> previous;
        Node<E> next;
        E element;

        public Node(Node<E> previous,Node<E> next,E element) {
            this.previous = previous;
            this.next = next;
            this.element = element;
        }
    }


    /*这个类有三个属性,既一个链表有头节点,尾节点,链表长度*/
    private Node<E> head;
    private Node<E> tail;
    private int size;

    /*无参构造*/
    public LinkList(){
    }
    /*全参构造*/
    public LinkList(Node<E> head,Node<E> tail,int size){
        this.head = head;
        this.tail = tail;
        this.size = size;
    }

    /*将元素插入到链表的尾部*/
    public boolean add(E element){
        Node<E> l = tail;
        Node<E> newNode = new Node<>(l, null, element);
        tail = newNode;
        if(l==null){
            head = newNode;
        }else{
            l.next=newNode;
        }
        size++;
        return true;
    }
    /*将元素插入到指定索引位置*/
    public void add(int index,E e){
        //要在链表头部插入数据
        if (index==0){
            head=new Node<>(head,null,e);
        }else{
            //获取上一个结点
         Node<E> prev=node(index-1);

            //获取下一个结点
           Node<E> next=prev.next;
          Node<E> newNode=new Node<>(prev,next,e);
            prev.next=newNode;
        }
        size++;
    }
    /*移除结点*/
    public E remove(int index){
       Node<E> node=head;
        if (index==0){
            head=node.next;
        }else{
            //待删除元素的上一位
          Node<E> prev=node(index-1);
            //待删除元素
            node=prev.next;
            prev.next=node.next;
        }
        size--;
        return node.element;
    }

    Node<E> node(int index) {
        //优化,判断查找的index和size的关系      100
        Node<E> x = head;
        for (int i = 0; i < index; i++) {
            x = x.next;
        }
        return x;
    }

    public E get(int index){//2
        return node(index).element;
    }
    public int size(){
        return size;
    }
    public E getFirst(){
        if (head==null)
            throw new NoSuchElementException();
        return head.element;
    }
    public E getLast(){
        if (tail==null)
            throw new NoSuchElementException();
        return tail.element;
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值