无序链表实现顺序查找(Java实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33054265/article/details/82763821

链表中的每个结点存储一个键值对,get()的实现即为遍历链表,equals()方法比较需要被查找的键和每个结点中的键,如果匹配成功就返回相应的值,否则返回null。put()的实现也是遍历链表,用equals()方法比较需要被查找的键和每个结点中的值,如果匹配成功就用第二个参数指定的值更新和该键相关联的值,否则我们就用给定的键值对创建一个新的结点并将其插入到链表的开头。

Java实现代码如下:

public class SequentialSearch<Key, Value> {
	private Node first;
	
	private class Node{
		Key key;
		Value val;
		Node next;
		
		public Node(Key key, Value val, Node next){
			this.key = key;
			this.val = val;
			this.next = next;
		}
	}
	
	public Value get(Key key){
		for(Node x = first; x != null; x = x.next){
			if(key.equals(first.key)){
				return x.val;
			}
		}
		return null;
	}
	public void put(Key key, Value val){
		for(Node x = first; x != null; x = x.next){
			if(key.equals(x.key)){
				x.val = val;
				return;
			}
		}
		first = new Node(key, val, first);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_33054265/article/details/82763821