什么是单链表

什么是单链表?


单链表(Linked List):由各个内存结构通过一个next指针链接在一起组成,每一个内存结构都存在后继内存结构(链尾除外),内存结构由数据域和next指针域组成。

单链表
Data 数据 + Next 指针,组成一个单链表的内存结构 ;
第一个内存结构称为 链头,最后一个内存结构称为 链尾
链尾的 Next 指针设置为 NULL [指向空];
单链表的遍历方向单一(只能从链头一直遍历到链尾)

插入
在链表头部插入:

public void addHead(T t){
	Node node = new Node(t);
	node.next = this.head;
	this.head = node;
	this.linkedSize++;//链表长度增加
}

在链表中间插入:

public void add(T t, int index){
	if(index<0 || index>linkedSize){
		throw new IllegalArgumentException("下标错误");
	}
	if(index == 0){
		this.addHead(t);
	}
	Node preNode = this.head;
	for(int i = 0; i<index-1; i++{
		preNode = preNode.next;
	}
	Node node = new Node(t);
	node.next = preNode.next;
	preNode.next = node;
	this.linkedSize++;
}

在链表尾部插入:

public void addTail(T t){
	this.add(t, this.linkedSize);//尾部next直接指向一个新的元素
}

删除:

public void remove(T t){
	if(head == null){
		System.out.println("无元素可删除");
		return;
	}
	if(!this.contains(t)){
		System.out.println("数据不存在");
		return;
	}
	while(head != null && head.t.equals(t)){
		//删除的元素为头结点
		head = head.next;
		this.linkedSize--;
	}
	Node cur = this.head;
	while(cur.next != null){
		if(cur.next.t.equals(t)){
			this.linkedSize--;
			cur.next = cur.next.next;
		}else{
			cur = cur.next;
		}
	}
}
		

遍历链表:

//某元素是否在链表上
public boolean isExist(T t){
	Node cur = this.head;
	while(cur != null){
		if(cur.t.equals(t)){
			return true;
		}
	}
	return false;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值