標籤:size 實現 hide rgs equal 簡單的 while i++ isp
大二學過資料結構的知識,只不過那時候用的是c語言,很多資料結構需要自己去實現,仍然記得拿指標寫雙向鏈表和二叉樹的那種痛苦,那個時候,因為沒有實際應用,所以總在懷疑,學資料結構是為了什嗎?
然後大三學習了Java,用Java也寫過一些代碼了,似乎資料結構課上講的那些東西仍然沒有在實際中用到,那麼,當初學的資料結構,到底用在哪?
後來在看Java的一些面試題,講到很多面試會問到ArrayList與LinkedList的區別,然後自己百度了一下,恍然大悟,原來資料結構在Java裡面天天在用,只不過用的是別人封裝好的類。
那麼,我也一定可以寫出這些資料結構,簡單的那種。。。。。。。
---------------------------------------------------------------------------------------------------------------------------
①ArrayList:
package test;import java.util.ArrayList;public class ArrayListTest<E> { //記錄數組長度 private static int max=10; //儲存資料 private static Object[] values=new Object[max]; //儲存當前數組長度 private static int len=0; public void add(E value) { if(len<max) { values[len]=value; len++; }else { max=max+10; values=new Object[max]; } } public boolean remove(E value) { Object[] values2=new Object[len-1]; int beRemovedNum=-1; for(int i=0;i<len;i++) { if(values[i]==value||values[i].equals(value)) { beRemovedNum=i; break; } } if(beRemovedNum!=-1&&beRemovedNum!=(len-1)) { for(int i=0;i<beRemovedNum;i++) { values2[i]=values[i]; } for(int i1=beRemovedNum;i1<len-1;i1++) { values2[i1]=values[i1+1]; } len--; values=values2; return true; }else if(beRemovedNum!=-1&&beRemovedNum==(len-1)){ for(int i=0;i<beRemovedNum;i++) { values2[i]=values[i]; } len--; if(len==0) { values=new Object[max]; return true; } values=values2; return true; }else { System.out.println("沒有這個資料,刪除失敗!"); return false; } } @Override public String toString() { if(len>0) { String arr="["; for(int i=0;i<len-1;i++) { arr=arr+values[i]+","; } arr=arr+values[len-1]+"]"; return arr; } return "[null]"; } //測試 public static void main(String[] args) { ArrayListTest<Integer> alt=new ArrayListTest<Integer>(); alt.add(1); System.out.println(alt); alt.remove(1); System.out.println(alt); alt.add(1); alt.add(1); alt.add(1); alt.add(4); alt.add(4); alt.add(5); System.out.println(alt); alt.remove(5); System.out.println(alt); alt.remove(100); System.out.println(alt); }}View Code
②LinkedList:
1 package LinkedListTest; 2 3 public class LinkedListTest<E> { 4 private Node<Object> tail=new Node<Object>(); 5 private Node<Object> head=new Node<Object>(); 6 7 public LinkedListTest() { 8 super(); 9 head.setData(null);10 head.setNext(tail);11 tail.setData(null);12 tail.setNext(null);13 }14 15 @Override16 public String toString() {17 Node<Object> node=new Node<Object>();18 node=head.getNext();19 String str="[";20 while(node.getNext().getData()!=null) {21 str=str+node.getData()+",";22 System.out.println(node.getData()+"-"+node.getNext());23 node=node.getNext();24 }25 str=str+node.getData()+"]";26 return str;27 }28 29 public void append(E value) {30 Node<Object> node=new Node<Object>();31 tail.setData(value);32 tail.setNext(node);33 tail=node;34 }35 36 public static void main(String[] args) {37 LinkedListTest<Integer> llt=new LinkedListTest<Integer>();38 llt.append(1);39 llt.append(2);40 llt.append(3);41 System.out.println(llt);42 }43 }LinkedListTest
Java資料結構