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();
        
    
        }
    
    }
  • 相关阅读:
    Codeforces Round #365 (Div. 2) D
    Codeforces Round #414 C. Naming Company
    Codeforces Round #365 (Div. 2) B
    LA 6893 The Big Painting(矩阵Hash)
    Gym100783C Golf Bot(FFT)
    POJ 2481 Cows(树状数组)
    POJ 2352 Stars
    POJ 2299 Ultra-QuickSort(树状数组+离散化)
    LightOJ 1341 Aladdin and the Flying Carpet(唯一分解定理)
    LightOJ 1356 Prime Independence(质因数分解+最大独立集+Hopcroft-Carp)
  • 原文地址:https://www.cnblogs.com/S-Mustard/p/8066803.html
Copyright © 2011-2022 走看看