当前位置: 首页 > article >正文

手写linklist实现查找插入删除以及获取链表长度

package LinkByHand;

public class LinkList {
	public Node head =null;
	//尾插法
	public void insert(int value) {
		Node node = new Node(value);
		if(head ==null) {
			head =node;
			return;
		}
		Node index = head;
		while(index.next!=null) {
			index =index.next;
		}
		index.next = node;
	}
	
	
	//头插法
	public void insertHead(int value) {
		Node node = new Node(value);
		if(head ==null) {
			head =node;
			return;
		}
		node.next =head;
		head=node;
	}
	
	//获取链表的长度
	public int getLen() {
		int count = 0;
		Node index = head;
		while(index!=null) {
			count++;
			index =index.next;
		}
		return count;
	}
	
	//链表中查数据
	public int search(int value) {
		int position =-1;
		Node index = head;
		while(index!=null) {
			position++;
			if(index.value==value) {
				
				return position;
		}
		index =index.next;
	}
		return -1;
	
	}	

	
	//指定位置插入
	public void insertAtPosition(int value,int position) {
		if(position<0||position>getLen()) {
			System.out.println("插入位置不合理");
			return;
		}
		
		if(position==0) {
			insertHead(value);
		}else  if(position==getLen()){
			insert(value);
		}else {
			Node node =new Node(value);
			Node index =head;
			Node pre = null;
			int current =0;
			while(index!=null) {
				if(current==position) {
					node.next = index;
					pre.next =node;
					return;
				}
				pre = index;
				index =index.next;
				current++;
			}
		}
		
		
		
	}
	
	//删除指定位置的节点
	public void deleteAtPosition(int position) {
		if(position<0||position>=getLen()) {
			System.out.println("删除位置不合理");
			return;
		}
		if(position==0) {
			head =head.next;
		}else {
			Node index = head;
			Node pre =null;
			int current =0;
			while(index!=null) {
				if(current==position) {
					//delete
					pre.next=index.next;
					return;
				}
				pre =index;
				index =index.next;
				current++;
			}
		}
	}
	
	
	
	
	//输出链表中的值	
	@Override
	public String toString() {
		String res="[ ";
		Node index =head;
		while(index!=null) {
			res+=index.value+" ";
			index =index.next;
		}
		res+="]";
		return res;
	}
}


http://www.kler.cn/a/581433.html

相关文章:

  • MAC 系统 多版本 JDK管理
  • 【网络安全工程】任务12:网络安全设备
  • IDEA中链接使用mysql数据库
  • 红警95游戏秘籍
  • 【Envi遥感图像处理】015:查看高光谱影像、光谱曲线
  • Spring Boot3整合Knife4j(4.5.0)
  • Python:正则表达式
  • LLMs基础学习(一)概念、模型分类、主流开源框架介绍以及模型的预训练任务
  • Vue计算侦听属性
  • AWS Bedrock 正式接入 DeepSeek-R1 模型:安全托管的生成式 AI 解决方案
  • 设计模式之原型模式:原理、实现与应用
  • 【Java】Websocket
  • Linux上位机开发实战(x86和arm自由切换)
  • SQLiteStudio:一款免费开源跨平台的SQLite管理工具
  • 【Troubleshot】Qt 长按按键 keyPressEvent keyReleaseEvent 自动重复问题
  • QT通过DeepSeek API获取公式正常显示的方法
  • postgresql 15.2 用pgbackup搭建备库后,主从复制一直无法启动
  • 卷积神经网络与计算机视觉:从数学基础到实战应用
  • LeetCode 1447 最简分数
  • flink依赖版本选择