JAVA顺序表的简单实现
生活随笔
收集整理的這篇文章主要介紹了
JAVA顺序表的简单实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import java.util.Scanner;class DATA{ //模擬一個班級的學生記錄String key;String name;int age;}class SLType{static final int MAXLEN = 100;DATA[] ListData = new DATA[MAXLEN+1]; int ListLen; //順序表已存結點的數量void SLInit(SLType sl){sl.ListLen = 0;}int SLLength(SLType sl){return (sl.ListLen);}//插入節點int SLInsert(SLType SL,int n , DATA data){int i ;if(SL.ListLen>=MAXLEN){System.out.println("順序表已滿,不能插入節點");return 0;}if(n<1 || n>SL.ListLen-1){System.out.println("插入序號有誤,不能插入節點");return 0;}//將順序表中的數據向后移動for(i = SL.ListLen; i >=n ; i--){SL.ListData[i+1] = SL.ListData[i];}SL.ListData[n] = data;SL.ListLen++;return 1;}//追加節點int SLAdd(SLType SL,DATA data){if(SL.ListLen>=MAXLEN){System.out.println("順序表已滿,不能插入節點");return 0;}SL.ListData[++SL.ListLen]=data;return 1;}//刪除節點int SLDelete(SLType SL,int n ){int i;if(n<1||n>SL.ListLen+1){System.out.println("序號輸入有誤,不能插入節點");return 0;}//往前挪for(i = n ; i<SL.ListLen;i++){SL.ListData[i] = SL.ListData[i+1];}SL.ListLen--;return 1;}//查找節點DATA SLFindByNum(SLType SL,int n){if(n<1||n>SL.ListLen+1){System.out.println("序號輸入有誤,不能插入節點");return null;}return SL.ListData[n];}//按照關鍵字查找節點int SLFindByCont(SLType SL,String key){int i;for(i = 1; i <= SL.ListLen ; i++){if(SL.ListData[i].key.compareTo(key)==0){return i;}}return 0;}//顯示所有節點int SLAll(SLType SL){int i;for(i = 1; i <=SL.ListLen ; i++){System.out.println(SL.ListData[i].key+"#"+SL.ListData[i].name+"#"+SL.ListData[i].age);}return 0;}}public class SequentialList {public static void main(String[] args) {int i;SLType SL=new SLType(); //定義順序表變量
// DATA data=new DATA(); //定義結點保存數據類型變量DATA pdata; //定義結點保存指針變量 String key; //保存關鍵字System.out.print("順序表操作演示!\n"); SL.SLInit(SL); //初始化順序表 System.out.print("初始化順序表完成!\n");Scanner input=new Scanner(System.in);do { //循環添加結點數據 System.out.print("輸入添加的結點(學號 姓名 年齡):"); DATA data=new DATA(); data.key=input.next();data.name=input.next();data.age=input.nextInt();if(data.age!=0) //若年齡不為0 {if(SL.SLAdd(SL,data)==0) //若添加結點失敗 {break; //退出死循環 }}else //若年齡為0 {break; //退出死循環}}while(true);System.out.print("\n順序表中的結點順序為:\n");SL.SLAll(SL); //顯示所有結點數據 System.out.print("\n要取出結點的序號:");i=input.nextInt(); //輸入結占點序號 pdata=SL.SLFindByNum(SL,i); //按序號查找結點 if(pdata!=null) //若返回的結點指針不為NULL{ System.out.printf("第%d個結點為:(%s,%s,%d)\n",i,pdata.key,pdata.name,pdata.age);}System.out.print("\n要查找結點的關鍵字:");key=input.next(); //輸入關鍵字 i=SL.SLFindByCont(SL,key); //按關鍵字查找 ,返回結點序號 pdata=SL.SLFindByNum(SL,i); //按序號查詢,返回結點指針 if(pdata!=null) //若結點指針不為NULL {System.out.printf("第%d個結點為:(%s,%s,%d)\n",i,pdata.key,pdata.name,pdata.age); }}}
總結
以上是生活随笔為你收集整理的JAVA顺序表的简单实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python学习之——利用urllib2
- 下一篇: 数据库生成T4模版在代码生成中的应用心得