不使用任何库函数,设计一个 跳表 。
- class Skiplist {
-
- int level=0;
-
- Node head=null;
-
- public Skiplist() {
-
- }
-
- public boolean search(int target) {
- Node cur=head;
- while(cur!=null){
- while(cur.right!=null&&cur.right.val
- cur=cur.right;
- }
- if(cur.right!=null&&cur.right.val==target){
- return true;
- }
- cur=cur.down;
- }
- return false;
- }
-
- public void add(int num) {
- int rLevel=1;
- while(rLevel<=level&&(Math.random()%2)==1){
- rLevel++; // 2
- }
- if(rLevel>level){
- level=rLevel;
- head=new Node(num,null,head);
- }
- Node cur=head,last=null;
- for(int l=level;l>0;l--){
- while(cur.right!=null&&cur.right.val
- cur=cur.right;
- }
- if(l<=rLevel){
- cur.right=new Node(num,cur.right,null);
- if(last!=null){
- last.down=cur.right;
- }
- last=cur.right;
- }
- cur=cur.down;
- }
- }
- // 擦除
- public boolean erase(int num) {
- Node cur=head;
- boolean seen=false;
- for(int l=level;l>0;l--){
- while(cur.right!=null&&cur.right.val
- cur=cur.right;
- }
- if(cur.right!=null&&cur.right.val==num){
- seen=true;
- // Node tmp=cur.right;
- cur.right=cur.right.right;
- }
- cur=cur.down;
- }
- return seen;
- }
- }
-
- /**
- * Your Skiplist object will be instantiated and called as such:
- * Skiplist obj = new Skiplist();
- * boolean param_1 = obj.search(target);
- * obj.add(num);
- * boolean param_3 = obj.erase(num);
- */
-
- public class Node {
- public int val;
- public Node right,down;
-
- Node() {
- }
-
- public Node(int val) {
- this.val = val;
- }
-
- Node(int val, Node right,Node down) {
- this.val = val;
- this.right = right;
- this.down = down;
- }
-
- /*public void add(int value) {
- Node p = this;
- while (p.right != null) {
- p = p.right;
- }
- Node newNode = new Node(value);
- p.right = newNode;
- }
- public void add(Node node) {
- Node p = this;
- while (p.right != null) {
- p = p.right;
- }
- p.right = node;
- }*/
- }
-
相关阅读:
汽车售后接待vr虚拟仿真实操演练作为岗位培训的重要工具和手段
深入理解强化学习——马尔可夫决策过程:马尔可夫决策过程和马尔可夫过程/马尔可夫奖励过程的区别
Python接口自动化测试post请求和get请求,获取请求返回值
org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException
Setup exvim enviroment
2023-09-09青少年软件编程(C语言)等级考试试卷(二级)解析
面试背诵版—操作系统
如何在 Objective-C 中实现多态性,并且它与其他面向对象编程语言的多态性实现有何差异?
前端工程化精讲第十三课 缓存优化:那些基于缓存的优化方案
基于SSM的高校餐厅防疫管理系统
-
原文地址:https://blog.csdn.net/m0_58961367/article/details/133721927