Posted on 2008-11-04 18:33
eyejava 閱讀(388)
評(píng)論(1) 編輯 收藏
旋轉(zhuǎn)數(shù)組的基本思想就是左移數(shù)組,但是我們需要保存”相對(duì)的首位置”,并將其值插入到最后位置
public class Test {
private char[] chArr;
private int size;
public Test(int size) {
chArr = new char[size];
size = 0;
}
//旋轉(zhuǎn)數(shù)組
public void rotate(int newSize) {//newSize為要旋轉(zhuǎn)數(shù)組的大小,從右邊算起
int p = size - newSize; //首位置
int i;
char t = chArr[p];
for (i = p+1; i < newSize; ++i) {//左移
chArr[i-1] = chArr[i];
}
chArr[i-1] = t;//將首位置的值插入到最后
}
public void display() {
for (int i = 0; i < chArr.length; ++i) {
System.out.print(chArr[i] + " ");
}
}
//向數(shù)組插入值
public void insert(char c) {
chArr[size++] = c;
}
//測(cè)試
public static void main(String[] args) {
Test test = new Test(3);
test.insert('c');
test.insert('a');
test.insert('t');
test.rotate(3);
test.display();
}
}//end test
結(jié)果應(yīng)該為:"a t c"