zoukankan      html  css  js  c++  java
  • 链表_有序链表(插入删除遍历)

    插入的节点位置有两种情况,一是有previous节点,而是没有previous节点

    //链结点
    public class Link {
        public long dData;
        public Link next;
        public Link(long dd) {
            dData=dd;    
        }
        public void displayLink() {
            System.out.print(dData+" ");
        }
    
    }
    public class SortedList {
        private Link first;
        public SortedList() {
            first=null;
        }
        //插入数据
        public void insert(long key) {
            Link newLink=new Link(key);
            //为找到插入点做准备
            Link previous=null;//记录插入点的左节点
            Link current=first;//记录插入点的右节点
            //寻找插入点
            while(current!=null&&key>current.dData) {//判断current!=null的原因是如果key是最大值,找不到比它大的,也需要退出循环
                //假设first端的数据是最小的
                previous=current;
                current=current.next;
            }
            //说明key是最小值
            if(previous==null)
                first=newLink;//改变first即可
            else
                previous.next=newLink;//不为空,与左侧需要连接
            
            newLink.next=current;//就算key是最大值,current会是null,这样也成立
            
        }
        //从first端删除
        public Link remove() {
            Link temp=first;
            first=first.next;
            return temp;
        }
        //遍历
        public void display() {
            System.out.println("List(Fist-->last):");
            Link current=first;
            while(current!=null) {
                current.displayLink();
                current=current.next;
            }
            System.out.println();
        }
    
    }
    public class Test {
    
        public static void main(String[] args) {
            SortedList theSortedList=new SortedList();
            theSortedList.insert(20);
            theSortedList.insert(40);
            theSortedList.display();
            theSortedList.insert(10);
            theSortedList.insert(30);
            theSortedList.insert(50);
            theSortedList.insert(55);
            theSortedList.display();
            theSortedList.remove();
            theSortedList.display();
        
    
        }
    
    }
  • 相关阅读:
    WebView loadData乱码问题
    记录常用工具
    android toolbar学习
    百度地图V5.0地图定位
    JS调JAVA代码
    开始使用Android Stdio
    记录下平时看到的好句子
    开发者必备网址
    android:ellipsize实现跑马灯效果总结
    seo查询命令
  • 原文地址:https://www.cnblogs.com/S-Mustard/p/8066803.html
Copyright © 2011-2022 走看看