<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>
链表实现查找
最新推荐文章于 2022-06-12 23:27:04 发布