- /*
- *
- * 單向鏈結
- */
- public class Single_Linked_List {
- public static void main(String[] args) {
- LinkedList nss = new LinkedList();
- for(int i = 1 ; i < 12; i++){
- nss.Insert("來福"+i, i+100, i);
- }
- nss.print();
- LinkedList nss2 = new LinkedList();
- for(int i = 1 ; i < 2; i++){
- nss2.Insert("雄威"+i, i+100, i);
- }
- //銜接
- nss.connect(nss2);
- nss.print();
- }
- }
- class Node{
- String name ;
- int score ;
- int num ;
- Node next ;
- Node(String n , int s , int nu){
- name = n ;
- score = s ;
- num = nu ;
- }
- }
- class LinkedList{
- Node frist ;
- Node last ;
- void print(){
- Node curr = frist ;
- while(curr != null){
- System.out.println(curr.name+" "+curr.score+" "+curr.num);
- curr = curr.next ;
- }
- if(frist == null) System.out.println("空串列") ;
- }
- void Insert(String n , int s , int nu){
- Node newNode = new Node(n,s,nu);
- if(frist == null){
- frist = newNode ;
- last = newNode ;
- }else{
- last.next = newNode ;
- last = last.next ;
- }
- }
- void remove(int num){
- if(frist.num == num){
- frist = frist.next ;
- }else if(last.num == num){
- Node curr = frist ;
- while(curr.next != last) curr = curr.next ;
- last = curr ;
- curr.next = null ;
- }else {
- Node tmp = frist , current = frist ;
- while(num != current.num){
- tmp = current ;
- current = current.next ;
- }
- tmp.next = current.next ;
- }
- }
- void Insert(int num , Node node){
- if(frist.num == num){
- node.next = frist ;
- frist = node ;
- }else if(last.num == num){
- last.next = node ;
- last = last.next ;
- }else{
- Node tmp = frist , current = frist ;
- try{
- while(num != current.num){
- tmp = current ;
- current = current.next ;
- }
- tmp.next = node ;
- node.next = current ;
- }catch(Exception ex){
- System.out.println("沒有符合座號");
- }
- }
- }
- void connect(LinkedList L2){
- last.next = L2.frist ;
- last = L2.last ;
- }
- }
2017年7月29日 星期六
(Java)單向鏈結
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言
注意:只有此網誌的成員可以留言。