链表_有序链表(插入删除遍历)

Posted S-Mustard

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表_有序链表(插入删除遍历)相关的知识,希望对你有一定的参考价值。

插入的节点位置有两种情况,一是有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();
    

    }

}

 

以上是关于链表_有序链表(插入删除遍历)的主要内容,如果未能解决你的问题,请参考以下文章

链表——链表删除冗余结点&插入结点到有序链表

有序的双链表的实现

[程序员代码面试指南]链表问题-向有序的环形链表插入新节点

二叉树

Java 实现有序链表

数据结构和算法——二叉树