最近学习java,用这门语言温习一下数据结构。
public class List { private int length; private int[] array; public List() { length = 0; array = new int[20]; } public boolean Insert(int value) { int j; if(length >= 20) { return false; } j = length - 1; while(j >= 0 && array[j] > value) { array[j+1] = array[j]; j--; } array[j+1] = value; length++; return true; } public boolean Delete(int index) { if(0 == length) { return false; } if(index < 1 && index > length) { return false; } int i = index - 1; while(i < (length - 1)) { array[i] = array[i+1]; i++; } length--; return true; } public void Clear() { length = 0; } public int ListLength() { return length; } public boolean IsEmpty() { if(length > 0) { return false; } else { return true; } } public int GetItem(int index) { return array[index-1]; } }还以为java函数中基本类型变量作为参数都是引用形式的,原来和C++一样。 线性表的使用要注意数组下标。 线性表的链式实现:
class List { int data; List next; List(int val,List L) { data = val; next = L; } List(int val) { data = val; next = null; } void SetNext(List L) { next = L; } void SetData(int val) { data = val; } int GetData() { return data; } List GetNext() { return next; } } //测试代码 public class test { public static void main(String []args){ List head = new List(0,null); List temp = head; for(int i=0;i<=9;i++) { List node = new List(i,null); temp.SetNext(node); temp = temp.GetNext(); } temp = head.GetNext(); while(null != temp) { System.out.println(temp.GetData()); temp = temp.GetNext(); } } }感觉java都用引用很方便,比C++使用大量的指针安全多了。内存也不用自己去析构,很方便。