链表实现查找

本文介绍了一种基于链表的数据结构实现查找、更新、删除等操作的方法。具体包括链表节点的设计、基本操作如获取指定键的值、插入新节点、删除指定键及其对应的值等,并提供了遍历显示链表所有值的功能。

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

<span style="font-size:18px;">/**
 * 链表实现查找
 * @author xxxu
 *
 */
public class SSST {
	//链表的头结点
	private Node first=null;
	private class Node{
		Integer key; //键
		String val;  //值
		Node next;   //下个节点地址
		public Node(Integer key,String val,Node next){
			this.key=key;
			this.val=val;
			this.next=next;
		}
	}
	//没有返回null
	public String get(Integer key){
		for (Node x = first;  x != null; x=x.next) {
			if(x.key==key){
				return x.val;
			}
		}
		return null;
	}
	/**
	 * 查找给定的键,找到则更新其值,否则在表中新建节点
	 * @param key
	 * @param val
	 */
	public void put(Integer key,String val){
		if(key!=null&&val!=null){
			for (Node x = first;  x != null; x=x.next) {
				if(x.key==key){
					x.val=val;
					return;
				}
			}
			first=new Node(key,val,first);
		}
	}
	//链表是否为空
	public boolean isEmpty(){
		if(size()==0){
			return true;
		}else{
			return false;
		}
	}
	//删除给定的键
	public String delete(Integer key){
		Node t=null;
		for (Node x = first;  x != null; x=x.next) {
			if(x.key==key){
				if(t!=null){
					t.next=x.next;
					return x.val;
				}else{
					first=x.next;
					return x.val;
				}
			}
			t=x;
		}
		return null;
	}
	//用数组形式返回所有的键
	public int[] keys(){
		int[] keys=new int[size()];
		int i=0;
		for (Node x = first;  x != null; x=x.next) {
			keys[i++]=x.key;
		}
		return keys;
	}
	//链表的大小
	public int size(){
		int N=0;
		for (Node x = first;  x != null; x=x.next) {
			N++;
		}
		return N;
	}
	//遍历链表的值
	public void show(){
		for (Node x = first;  x != null; x=x.next) {
			System.out.print(x.val+" ");
		}
		System.out.println();
	}
}</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值