码迷,mamicode.com
首页 > 编程语言 > 详细

java语言实现顺序表

时间:2015-06-09 17:29:11      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

public class SqList {

	private int[] data;
	private int length;
	public SqList() {
		data = new int[30];
		length = 0;
	}
	
	public boolean empty() {
		return length == 0;
	}
	
	public int length() {
		return length;
	}
	
	public void display() {
		int i;
		for(i=0; i<length-1; i++) {
			System.out.print(data[i]+"->");
		}
		System.out.println(data[i]);
	}
	
	public int[] get(int i) {
		int[] arr = new int[2];
		if(i<1 || i>length) {
			arr[0] = 0;
			return arr;
		}
		arr[0] = 1;
		arr[1] = data[i-1];
		return arr;
	}
	
	public int locate(int e) {
		int i=0;
		while(i<length && data[i]!=e) {
			i++;
		}
		if(i == length) 
			return 0;
		else 
			return i+1;
	}
	public boolean insert(int i, int e) {
		
		if(i<1 || i>length) {
			return false;
		}
		i--;
		for(int j=length; j>i; j--) {
			data[j] = data[j-1];
		}
		data[i] = e;
		length ++;
		return true;
		
	}  
	public int[] delete(int i) {
		int[] arr = new int[2];
		if(i<1 || i>length) {
			arr[0] = 0;
			return arr;
		}
		i--;
		arr[0] = 1;
		arr[1] = data[i];
		for(int j=i; j<length-1; j++) {
			data[j] = data[j+1];
		}
		length--;
		return arr;
	}
	
	public void create(int[] arr, int n) {
		for(int i=0; i<n; i++) {
			data[i] = arr[i];
		}
		length = n;
	}
	public static void main(String[] args) {
		int[] arr = new int[]{5,6,1,6,9,3,7,8};
		SqList list = new SqList();
		list.create(arr, arr.length);
		System.out.println(list.empty());
		System.out.println(list.length());
		list.display();
		if(list.get(3)[0] == 0) {
			System.out.println("error");
		} else {
			System.out.println(list.get(3)[1]);
		}
		if(list.get(0)[0] == 0) {
			System.out.println("error");
		} else {
			System.out.println(list.get(0)[1]);
		}
		
		System.out.println(list.locate(6));
		System.out.println(list.locate(4));
		if(!list.insert(0, 4)) {
			System.out.println("error");
		} else {
			list.display();
		}
		if(!list.insert(4, 4)) {
			System.out.println("error");
		} else {
			list.display();
		}
		int[] res = list.delete(0);
		if(res[0] == 0) {
			System.out.println("error");
		} else {
			System.out.println("delete "+res[1]);
			list.display();
		}
		res = list.delete(6);
		if(res[0] == 0) {
			System.out.println("error");
		} else {
			System.out.println("delete "+res[1]);
			list.display();
		}
		
	}
	
}


结果:

false
8
5->6->1->6->9->3->7->8
1
error
2
0
error
5->6->1->4->6->9->3->7->8
error
delete 9
5->6->1->4->6->3->7->8

java语言实现顺序表

标签:

原文地址:http://blog.csdn.net/qhairen/article/details/46426705

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!