Java---单链表

#java学习经验总结------单链表的建立与结点的增删

在该链表结点有data数据,并且还有cpu,分给cpu随机的时间片,根据时间片大小进行结点data的排序

链表结点的建立

class LinkNode{//结点的建立  
    private int data;
    private int cpu;
    public LinkNode next;
    public LinkNode(int data) {
        this.data=data;
        
    }
    public int getCpu() {
        return cpu;
    }
    public void setCpu(int cpu) {
        this.cpu = cpu;
    }
    public int getData() {
        return data;
    }
    public void setData(int data) {
        this.data = data;
    }
    

链表的构建过程以及添加节点、删除节点

class Linklist{
    private LinkNode front;
    private LinkNode current;
    public Linklist() {
        current=front=new LinkNode(0);//单链表头节点必须对象化,否则会导致空指针异常
    
        
    }
    public void add(int data) {//链表的添加
        LinkNode Node = new LinkNode(data);
        while(current.next!=null) {
            current=current.next;
        }
        current.next=Node;
    }
    public void print() {//链表的打印
        LinkNode node =front.next;
        while(node!=null) {
            System.out.println(node.getData()+" "+node.getCpu());
            node=node.next;
        }
        System.out.println("======================================");
    }   
    public void sort(int temp) {//对链表进行排序
        int a;
        int b;
        for(int i=0;i<temp-1;i++)
        {
            
            LinkNode now=front.next;
            for(int j=0;j<temp-i-1;j++) {
                if(now.getCpu()>now.next.getCpu()) {
                    a=now.getData();
                    b=now.next.getData();
                    now.setData(b);
                    now.next.setData(a);
                    a=now.cpu;
                    now.cpu=now.next.cpu;
                    now.next.cpu=a;
                    System.out.println();
                    
                }
                now=now.next;
            }
        }
        
    }
    public void delete(int num) {//链表的删除
        int i=1;
        LinkNode node=front;
        while(i<num) {
            node=node.next;
            i++;
        }
    
        node.next=node.next.next;
        
    }
}

猜你喜欢

转载自www.cnblogs.com/Feihigh/p/12198858.html