2017年7月29日 星期六

(Java)單向鏈結

  1. /* 
  2.  *  
  3.  * 單向鏈結 
  4.  */  
  5. public class Single_Linked_List {  
  6.   
  7.   public static void main(String[] args) {  
  8.   LinkedList nss = new LinkedList();  
  9.   for(int i = 1 ; i < 12; i++){  
  10.    nss.Insert("來福"+i, i+100, i);  
  11.   }  
  12.   nss.print();  
  13.   LinkedList nss2 = new LinkedList();  
  14.   for(int i = 1 ; i < 2; i++){  
  15.    nss2.Insert("雄威"+i, i+100, i);  
  16.   }  
  17.   //銜接  
  18.      nss.connect(nss2);  
  19.   nss.print();  
  20.     
  21.  }  
  22. }  
  23. class Node{  
  24.  String name ;  
  25.  int score ;  
  26.  int num ;  
  27.  Node next ;  
  28.  Node(String n , int s , int nu){  
  29.   name = n ;  
  30.   score = s ;  
  31.   num = nu ;  
  32.  }  
  33. }  
  34. class LinkedList{  
  35.  Node frist ;   
  36.  Node last ;  
  37.  void print(){  
  38.   Node curr = frist ;  
  39.   while(curr != null){  
  40.    System.out.println(curr.name+" "+curr.score+" "+curr.num);  
  41.    curr = curr.next ;  
  42.   }  
  43.   if(frist == null) System.out.println("空串列") ;  
  44.  }  
  45.     void  Insert(String n , int s , int nu){  
  46.   Node newNode = new Node(n,s,nu);  
  47.   if(frist == null){  
  48.    frist = newNode ;  
  49.    last = newNode ;  
  50.   }else{  
  51.    last.next  = newNode ;  
  52.    last = last.next ;  
  53.    }     
  54.  }  
  55.     void remove(int num){  
  56.      if(frist.num == num){  
  57.       frist = frist.next ;  
  58.      }else if(last.num == num){  
  59.       Node curr = frist ;  
  60.       while(curr.next != last) curr = curr.next ;  
  61.       last = curr ;  
  62.       curr.next = null ;  
  63.      }else {  
  64.       Node tmp = frist , current = frist ;   
  65.       while(num != current.num){   
  66.        tmp = current ;  
  67.        current = current.next ;  
  68.       }  
  69.       tmp.next = current.next ;  
  70.      }  
  71.     }  
  72.     void Insert(int num , Node node){  
  73.      if(frist.num == num){  
  74.       node.next = frist ;  
  75.       frist = node ;    
  76.      }else if(last.num == num){  
  77.       last.next = node ;  
  78.       last = last.next ;  
  79.      }else{  
  80.       Node tmp = frist , current = frist ;   
  81.       try{  
  82.          
  83.       while(num != current.num){   
  84.        tmp = current ;  
  85.        current = current.next ;  
  86.       }  
  87.         
  88.       tmp.next = node ;  
  89.       node.next = current ;  
  90.       }catch(Exception ex){  
  91.        System.out.println("沒有符合座號");  
  92.       }  
  93.      }  
  94.     }  
  95.     void connect(LinkedList L2){  
  96.      last.next = L2.frist ;  
  97.      last = L2.last ;  
  98.     }  
  99. }  

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。