方法一:
package cn.node;
import java.util.LinkedList;
public class SimpleList<E> {
private LinkedList<E> linkedList;
public SimpleList(){
linkedList = new LinkedList<E>();
}
/**
* 添加元素
* 链表添加元素的方式就是最后一个元素的指针指向添加的元素,此处
* 采用linklist来模拟
* @param e
*/
public void insert(E e){
linkedList.addLast(e);
}
//删除元素
public boolean delete(int i){
if(linkedList.size() <= i)
return false;
linkedList.remove(i);
return true;
}
//get元素
public E getElement(int i){
if(linkedList.size() <= i)
return null;
return linkedList.get(i);
}
//获取链表的长度
public int getLength(){
return linkedList.size();
}
}
方法二:
public class Node<T> {
//数据域
public T data;
public Node<T> next; //链表的指向下一个节点的指针
}
package cn.node;
/***
* java链表的实现
*
* @author join
*
* @param <T>
*/
public class SimpleLinked<T> {
// 创建链表的节点
private Node<T> tail;
private Node<T> head;
private int size;
/****
* 构造方法中初始化构造链表的头结点
*
* @param t
*/
public SimpleLinked() {
head = new Node<T>();
size = 0;
}
/***
*
* @param t 要插入的元素
* @return
*/
public boolean insertFirstEle(T t){
head.data = t;
tail = head.next = new Node<T>();
size++;
return true;
}
/***
*
* @param t
* @return
*/
public boolean insertLastEle(T t){
if(size == 0){
insertFirstEle(t);
return true;
}
Node<T> node = tail;
node.data = t;
tail = node.next = new Node<T>();
size++;
return true;
}
/***
*
* @param t
* @return
* @throws Exception
*/
public boolean deleteEle(T t) throws Exception{
if(head == null){
throw new Exception("SimpleLinked is null");
}
if(head.data.equals(t)){
if(head.next != null) {
head = head.next;
size--;
}else{
size = 0;
}
}else{
Node<T> pre = head;
Node<T> cur = head.next;
while(cur.data != null){
if(cur.data.equals(t)){
pre.next = cur.next;
size--;
}
pre = cur;
cur = cur.next;
}
}
return true;
}
public T getEle(int loc){
if(loc > size){
return null;
}
Node<T> node = head;
for (int i = 0; i < loc; i++) {
node = node.next;
}
return node.data;
}
/**
* 获取链表的大小
* @return
*/
public int getSize(){
return size;
}
}