赞
踩
public class OrderLink { private Node head; private int size; private class Node{ private int data; private Node next; public Node(int data) { this.data = data; } } public OrderLink() { head = null; size = 0; } public void add(int data) { Node node = new Node(data); if(size==0) { head = node; }else { Node currentNode = head; Node previousNode = head; while(currentNode != null && currentNode.data<data) { previousNode = currentNode; currentNode = currentNode.next; } previousNode.next = node; node.next = currentNode; } size++; } public void remove() { if(size==0) { throw new IndexOutOfBoundsException(); }else if(size==1){ head=null; }else { head = head.next; } size--; } public void display() { if(size==0) { System.out.println("[]"); }else if(head.next ==null) { System.out.println("["+head.data+"]"); }else { Node node = head; int tempSize=size; while(tempSize>0) { if(node==head) { System.out.print("["+node.data+"->"); }else if(node.next == null) { System.out.print(node.data+"]"); }else { System.out.print(node.data+"->"); } node = node.next; tempSize--; } System.out.println(); } } }
public class TestOrderLink { public static void main(String[] args) { OrderLink ol = new OrderLink(); ol.display(); ol.add(1); ol.display(); ol.add(2); ol.display(); ol.add(5); ol.display(); ol.add(4);; ol.display(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。