package com.gosaint.collection;
/**
* @Author: gosaint
* @Description:
* @Date Created in 21:25 2021/2/20
* @Modified By:
*/
public class TsLinked<E> {
/**
* 指针指向第一个结点。
*/
private Node<E> first;
/**
* 链表的长度
*/
public int size;
/**
* 单向链表的实现
*
* @return
*/
private static class Node<E> {
E item;
Node<E> next;
public Node(final E item, final Node<E> next) {
this.item = item;
this.next = next;
}
}
/**
* 获取结点
* 1->3->4-7-null
*
* @param index
* @return
*/
Node<E> node(int index) {
//遍历链表
Node<E> x = first;
for (int i = 0; i < index; i++) {
x = x.next;
}
return x;
}
/**
* 解除元素的引用
*
* @param x
* @return
*/
E unlink(Node<E> x) {
E item = x.item;
//获取当前结点的下一个结点
Node<E> next = x.next;
//将当前结点的下一个引用置为空
x.next = null;
//将next赋值给当前结点
x = next;
size--;
return item;
}
/**
* 添加数据
*
* @param e
* @return
*/
public boolean add(final E e) {
Node<E> x = new Node<>(e, null);
if (size == 0) {
//空链表
this.first = x;
} else {
//1->3->4-7-null
//链表非空。插入到结尾。获取最后一个结点。然后将最后一个结点的引用置为当前结点
Node<E> lastNode = node(size-1);
lastNode.next = x;
}
size++;
return true;
}
/**
* @param index 索引
* @return 返回元素
*/
public E get(int index) {
return node(index).item;
}
public int size() {
return this.size;
}
public boolean isEmpty() {
return size == 0 ? true : false;
}
public boolean contains(final Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item.equals(o)) {
return true;
}
}
}
return false;
}
/**
* 删除元素 1->3->4-7-null 比如删除4.直接将当前3->7.即接触删除元素的引用
*
* @param o
* @return
*/
public boolean remove(final Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item.equals(o)) {
unlink(x);
return true;
}
}
}
return false;
}
/**
* 删除指定位置元素
*
* @param index
* @return
*/
public E remove(int index) {
return unlink(node(index));
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(size * 2 + 1);
sb.append("TsLinked{");
for (int i = 0; i < size; i++) {
Node<E> node = node(i);
E item = node.item;
if (i == size - 1) {
sb.append(item);
} else {
sb.append(item + "->");
}
}
sb.append("}");
return sb.toString();
}
}
实现的API如下:

1710

被折叠的 条评论
为什么被折叠?



