線性表java實現
阿新 • • 發佈:2018-10-14
out rtl java 線性表 insert size lists args java實現
順序表
public class SequenceList { /* * content,節點內容 * location,節點在表中的位置(序號) * */ private String content; private int location; SequenceList(String content, int location){ this.content = content; this.location = location; } SequenceList(){ this.content = "-1"; this.location = -1; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getLocation() { return location; } public void setLocation(int location) { this.location = location; } }
順序表的各個操作
遍歷
/* * 遍歷順序表 * */ public static void showList(SequenceList[] list){ for(SequenceList one:list){ if(one!=null) System.out.println("location = "+one.getLocation()+",content = "+one.getContent()); else break; } }
插入
/* * 插入節點 * */ public static void insertItem(SequenceList[] list, SequenceList item, int currentListLength, int insertLocation){ list[currentListLength] = new SequenceList(); if(currentListLength<insertLocation){ System.out.println("插入位置不在線性表內"); }else if(currentListLength==insertLocation+1){ System.out.println("線性表已滿"); }else { for(int i = currentListLength;i>insertLocation;i--){ list[i] = list[i-1]; list[i].setLocation(i);//重新設置節點位置 } list[insertLocation] = item; currentListLength++; } }
獲得特定位置的節點
/* * 獲得特定位置的節點 * */ public static SequenceList getSpecificItem(SequenceList[] list, int location){ for(SequenceList one:list){ if(one.getLocation()==location){ return one; } } return null; }
獲得某個節點的位置
/* * 獲得某個節點的位置 * */ public static int getItemLocation(SequenceList[] list, String content){ for(SequenceList one:list){ if(one.getContent().equals(content)){ return one.getLocation(); } } return -1; }
刪除某個位置的節點
/* * 刪除節點 * */ public static void deleteItem(SequenceList[] list, int location){ for(int i = location;;i++){ if(list[i+1]==null){ list[i] = null; break; } list[i] = list[i+1]; list[i].setLocation(i);//重新設置節點位置 } }
測試
public static void main(String[] args) { SequenceList[] lists = new SequenceList[20]; for(int i = 0;i < 6;i++){ lists[i] = new SequenceList(); lists[i].setContent(String.valueOf(i)); lists[i].setLocation(i); } insertItem(lists,new SequenceList("a",5),6,5); showList(lists); deleteItem(lists,5); showList(lists); System.out.println("5號位的內容是"+getSpecificItem(lists,5).getContent()); System.out.println("內容為2的位置是"+getItemLocation(lists,"2")); }
結果
location = 0,content = 0 location = 1,content = 1 location = 2,content = 2 location = 3,content = 3 location = 4,content = 4 location = 5,content = a location = 6,content = 5 location = 0,content = 0 location = 1,content = 1 location = 2,content = 2 location = 3,content = 3 location = 4,content = 4 location = 5,content = 5 5號位的內容是5 內容為2的位置是2
鏈表
持續更新
線性表java實現