天天看點

連結清單-有序連結清單操作

import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.BufferedReader;/**
  * Class SortedLink Description 有序連結清單,首先的搜尋連結清單,直到找到合适的位置,它恰好在第一個比它大的資料項的前面,
  * 主要是插入是必須使整個連結清單有序。 Company OpenData Author Chenlly Date 09-03-05 Version 1.0
  */class Link {
  public Long lData;
  public Link next; // 構造方法
  public Link(Long lData) {
   this.lData = lData;
  } // 顯示連結清單資訊
  public void displayLink() {
   System.out.println("" + lData + ",");
  }
 }public class SortedLink {
  private Link firstLink;
  private int size; public SortedLink() {
   // to do something
   firstLink = null;
  } // 構造一個新節點
  public Link createNode(Long lData) {
   Link link = new Link(lData);
   return link;
  } // 插入一個新節點使整個連結清單有序
  public void insert(Link link) {
   Link current = firstLink;
   Link previous = null;
   //連結清單從頭到尾,按升序排列
   while (current != null && current.lData < link.lData) {
    previous = current;
    current = current.next;
   }
   if (previous == null) {
    firstLink=link;//第一次插入的情況
   } else {
    link.next = current;
    previous.next = link;
   }
  } // 删除一個最小的節點
  public Link remove() throws Exception {
   if (firstLink==null){
    throw new Exception ("WARN - 連結清單中還沒有資料項,不能做删除操作"); 
   }
   Link temp = firstLink;
   firstLink = firstLink.next;
   return temp;
  } // 顯示連結清單資訊
  public void display() {
   System.out.println("from first-->end:");
   Link current = firstLink;
   while (current != null) {
    current.displayLink();
    current = current.next;
   }
  } // 從鍵盤輸入資料
  public static String readStr() {
   InputStreamReader ir = new InputStreamReader(System.in);
   BufferedReader br = new BufferedReader(ir);
   String str = "";
   try {
    str = br.readLine();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return str;
  } public static void main(String[] args) {
   System.out.println("連結清單基本算法請選擇:");
   System.out.println("1 插入新節點");
   System.out.println("2 删除新節點");
   System.out.println("3 顯示連結清單資訊");
   System.out.println("4 退出");
   SortedLink sortedLink = new SortedLink();
   while (true) {
    System.out.println("請輸入操作序列:");
    int op = Integer.parseInt(SortedLink.readStr());
    switch (op) {
    case 1:
     System.out.println("請輸入節點資訊");
     Long lData = new Long(Long.parseLong(SortedLink.readStr()));
     Link newLink = sortedLink.createNode(lData);
     sortedLink.insert(newLink);
     break;
    case 2:
     Link oldLink = null;
     try {
      oldLink = sortedLink.remove();
     } catch (Exception ex){
      ex.printStackTrace();
     }
     if (oldLink != null) {
      System.out.println("删除的節點資訊:" + oldLink.lData);
     } else {
      System.out.println("删除節點失敗");
     }
     break;
    case 3:
     sortedLink.display();
     break;
    case 4:
    default:
     System.exit(0);
    }// end switch
   }// end while
  }
 }      

繼續閱讀