当前位置:   article > 正文

有序链表OrderLink

有序链表

1.实现有序链表

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();
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

2.使用

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();
	}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/858775
推荐阅读
相关标签
  

闽ICP备14008679号