链表基础操作——结构、头插、尾插、任意位置插入、findKey

链表:逻辑上有线性关系,物理存储不保证连续

//结点{ 值,下一个结点的引用 }
class Node{
    public int value;   //保存的是有效数据
    public Node next;  //下一个结点的线索(引用)

    Node(int value){
        this.value = value;
        this.next = null;
    }
}
//定义头节点
private Node head;  
//链表头插
void addFirst(int value){

    Node node = new Node(value);
    //1.判断链表为空
    if(this.head == null){
        this.head = node;
        return;
    }
	//2.前头节点置于node之后
    node.next = this.head;
    head = node;//更换新的头节点
}
//链表尾插
void addLast(int value){

	Node node = new Node(value);
	//1.判断空链表
	if(this.head == null){
		this.head = node;
    }
	//2.定义节点变量cur,遍历至链表最后一个节点
    Node cur = this.head; 
    while(cur.next != null){  //cur.next 为倒数第二个节点
    	cur = cur.next; //找到最后一个节点
    }
	//3.尾插
    cur.next = node;
}
//链表包含key
boolean findKey(int key){

	Node node = new Node(key);
	//1.判断空链表
	if(this.head == null){
		throw new Error("LinkedList is null!");
	}
	//2.定义节点变量cur进行遍历,findKey
	Node cur = this.head;
	while(cur != null){
		if(cur.value == key){
			return true;
		}
		cur = cur.next;
	}
	return false;
}
//链表大小
int size(){

	int count = 0;
	//1.判断空链表
	if(this.head == null){
		return 0;
	}
	//2.定义变量节点cur,遍历整个链表
	Node cur = this.head;
	while(cur != null){
		count++;
		cur = cur.next;
	}
	return count;
}
//链表任意给定位置插入节点

//1.找到位置节点
Node searchIndex(int index){
	//1.判断index合法
	if(index < 0 || index > this.size()){
		throw new Error("The index is illegal!");
	}
	//2.定义节点变量,通过遍历找到index下标所指节点的前一个节点
	Node cur = this.head;
	while(index - 1 != 0){
		cur = cur.next;
		index--;
	}
	//3.返回前一个节点
	return cur;
}

//2.任意位置插入
void addIndex(int index, int value){
	//1.判断index的值:index == 0 即为下标为0的节点,即链表第一个节点 -> 头插
	if(index == 0){
		addFirst(value);
		return;
	}
	//2.index == this.size() 即为下标为链表最大节点长度,即链表最后一个节点 -> 尾插
	if(index == this.size()){
		addLast(value);
		return;
	}
	//3.index 不是边界值而是中间值,则获取index所指节点
	Node node = new Node(value);
	Node cur = searchIndex(index); 
	//4.插入新节点
	node.next = cur.next; //将index所指的节点的前一个节点的next指向新节点的next
	cur.next = node;  //更新index位置的节点
}
//打印链表
void display(){
	//1.判断空链表
	if(this.head == null){
		System.out.println("LinkedList is null");
		return;
	}
	//遍历打印
	Node cur=  this.head;
	while(cur != null){
		if(cur.next != null){
			System.out.print(cur.value + "->");
		}else{
			System.out.print(cur.value);
		}
		cur = cur.next;
	}
	System.out.println();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值