javaは行列とチェーンを使って列の例を実現します。
5241 ワード
(1)行列で実行される列:
//
public interface NetJavaList {
public void add(Student t); //
public Student get(int index);// , ,
public int size();
}
学生クラスを定義します。
class Student {
private String name ; // ,
private int score ;
public Student(String name , int score){
this.name = name ;
this.score = score ;
}
public void printInfo(){
System.out.println(" "+name + " "+score ) ;
}
}
カスタムインターフェースを実現
public class STList implements NetJavaList{
private Student[] str = new Student[0] ;
//
public void add(Student t) {
Student[] src = new Student[str.length+1];
for(int i=0;i src[i]=str[i] ;
}
src[str.length]=t ;
str = src ;
}
//
public Student get(int index) {
Student t = str[index];
return t;
}
//
public int size() {
return str.length;
}
}
メイン関数クラスを書いて、次の列を実現します。
public class Manager {
public static void main(String[] args) {
STList sil = new STList() ;
for(int i=0;i<5;i++){
Student st = new Student("name"+i,i*10);
sil.add(st);
}
printList(sil) ;
}
//
public static void printList(STList t){
for(int i=0;i Student f =t.get(i);
f.printInfo();
}
}
}
(2)チェーン実現の行列 まずノードクラスを定義します。
public class LinkNode {
private Object obj ; //
private LinkNode next ; //
//
public LinkNode(Object obj){
this.obj = obj ;
}
public Object getObj(){
return obj ;
}
public void setObj(Object obj){
this.obj = obj ;
}
public LinkNode getNext(){
return next ;
}
public void setNext(LinkNode next){
this.next =next ;
}
}
そして、キューの実現方法クラスを書きます。
public class LinkList {
public static LinkNode root ;//
public LinkNode last = null ;//
public static void main(String ara[]){
LinkList df = new LinkList() ;
df.add(1);
df.add(2);
df.add(3);
df.printLinkList(root);
df.move(root,2) ;
df.move(root,2) ;
df.printLinkList(root);
}
/*
*
*/
public void add(Object obj){
//
LinkNode t = new LinkNode(obj);
if(root ==null){
root = t ;
last = root ;
}else{
last.setNext(t);
last = t ;
}
}
/*
*
*/
public void printLinkList(LinkNode root){
if(null != root){
Object data = root.getObj();
System.out.println(data);
LinkNode temp = root.getNext();
printLinkList(temp) ;
}
}
/*
*
*/
public LinkNode move(LinkNode root,int index){
if(this.getLength() throw new RuntimeException(" :"+index +
",size:" +this.getLength()) ;
}else{
int count = 1 ;LinkNode sd = root ;
while(count!=index-1){
sd = sd.getNext();
}
sd.setNext(sd.getNext().getNext());
return root ;
}}
/*
*
*/
public int getLength(){
int count = 0 ;
if(root==null){
return count ;
}
LinkNode node =root.getNext();
while(null != node){
count ++ ;
node=node.getNext();
}
//System.out.println((count+1));
return count+1 ;
}
}