Java数据结构--单链表

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


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

链表结点的建立

class LinkNode{//结点的建立	
	private int data;
    private int cpu;
	public LinkNode next;
	public LinkNode(int data) {
		this.data=data;
        this.cpu=new Random().nextInt(10) + 1;;
        
	}
	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;
		
	}
}

posted on 2020-01-15 21:25  Fei_high  阅读(207)  评论(0)    收藏  举报

导航