Java实现带泛型的双向链表

本文详细介绍了一种双向链表的Java实现方式,包括链表的初始化、节点添加、节点删除及查找等核心操作。通过泛型的应用,使得该双向链表能够存储任意类型的数据,提高了其实用性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

双向链表(Java实现)带泛型

package whh.sort;
public class LinkedList<T> {
	private int key;
	private LinkedList<T>head;
	private LinkedList<T>tail;
	private LinkedList<T>next;
	private LinkedList<T>pre;
	private T data;
	private int len;
	//初始化链表
	public LinkedList(int key,T data) {
		this.data = data;
		this.key = key;
		head = this;
		tail = head;
		len++;
	}
	//添加节点
	public void add(LinkedList<T> node){
		tail.next = node;
		node.pre = tail;
		tail = node;
		len++;
	}
	//删除节点
	public void del(int key){
		//头结点
		if(head.key == key){
			head = head.next;
			head.pre = null;
			len--;
		}else if(tail.key == key){
			tail = tail.pre;
			tail.next = null;
			len--;
		}else{
			LinkedList<T> current = get(key);
			if(current == null){
				System.out.println("删除失败");
				return;
			}
			current.pre.next = current.next;
			current.next.pre=current.pre;
			current = null;
			len--;
		}
	}
	//根据key获取节点
	public LinkedList<T> get(int key){
		if(head.key == key){
			return head;
		}else if(tail.key == key){
			return tail;
		}else{
			LinkedList<T> temp = head;
			while(temp!=null){
				if(temp.key == key){
					break;
				}
				temp = temp.next;
			}
			return temp;
		}
	}
	//递归显示链表内容
	public void show(){
		System.out.println(head);
		if(head.next!=null){
			head.next.show();
		}
	}
	//测试
	public static void main(String[] args) {
		LinkedList<Integer> l = new LinkedList<Integer>(1, 1);
		for (int i = 2; i < 10; i++) {
			l.add(new LinkedList<Integer>(i, i));
		}
		l.show();
		System.out.println("头结点");
		System.out.println(l.head);
		System.out.println("尾巴结点");
		System.out.println(l.tail);
		System.out.println("*************");
		l.del(1);
		l.del(10);
		System.out.println(l.head.pre);
		l.show();
		System.out.println(l.len);
		System.out.println(l.get(7));
		System.out.println(l.get(4).pre);
		System.out.println(l.get(2).next);
	}
	@Override
	public String toString() {
		return "LinkedList [key=" + key + ", data=" + data + "]";
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值