文章目录
利用给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;
}
}