关于应用Java创建泛型创建链表

本文介绍两种Java链表的实现方式,一种使用Java内置的LinkedList,包括添加、删除、获取元素等操作;另一种从零构建单链表,涵盖插入、删除元素及获取指定位置元素的方法。

方法一:

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;

}



}










































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值