標籤:
1.要求:有一群人圍成一圈數數,逢3退1人,要求算出最後留下來的人的下標
2.用物件導向思想,有三個步驟:
(1)有哪些類:找名詞--"有一群人圍成一圈",所以有類People,PeopleCircle
(2)有哪些屬性方法
(3)類的關係
3.代碼:
1 package Test; 2 3 public class Count3Quit1$2 { 4 5 public static void main(String[] args) { 6 PeopleCircle pc = new PeopleCircle(500); 7 int countNum = 0; 8 9 People del = pc.getLast(); //先把位置指向last,一開始計數就會指向第一個元素 10 while(pc.getCount() > 1){ 11 countNum++; 12 del = del.getRight();//跟蹤當前的元素位置,且到了末尾會自動從頭開始跟蹤 13 if(countNum == 3){ 14 pc.delete(del); 15 countNum = 0; 16 } 17 } 18 System.out.println(pc.getCount()); 19 System.out.println(pc.getFirst()); 20 System.out.println(pc.getLast()); 21 } 22 23 } 24 25 //要求:有一群人圍成一圈數數,逢3退1人,要求算出最後留下來的人的下標 26 //用物件導向思想,有三個步驟: 27 //(1)有哪些類(2)有哪些屬性方法(3)類的關係 28 29 //(1)有哪些類?找名詞--"有一群人圍成一圈",所以有類People,PeopleCircle 30 class People{ 31 32 private int id; 33 private People left; 34 private People right; 35 36 public People(int id) { 37 super(); 38 this.id = id; 39 } 40 41 public People getLeft() { 42 return left; 43 } 44 45 public void setLeft(People left) { 46 this.left = left; 47 } 48 49 public People getRight() { 50 return right; 51 } 52 53 public void setRight(People right) { 54 this.right = right; 55 } 56 57 @Override 58 public String toString() { 59 return "People-"+id; 60 } 61 } 62 63 class PeopleCircle{ 64 65 private int count = 0; 66 67 public int getCount() { 68 return count; 69 } 70 71 public PeopleCircle(int count) { 72 for(int i = 0; i < count ; i++){ 73 add(); 74 } 75 } 76 77 private People first; 78 public People getFirst() { 79 return first; 80 } 81 82 private People last; 83 84 public People getLast() { 85 return last; 86 } 87 88 public void add(){ 89 People p = new People(count); 90 if(count <= 0 ){ 91 p.setLeft(p); 92 p.setRight(p); 93 first = p; 94 last = p; 95 count++; 96 }else { 97 last.setRight(p); 98 p.setLeft(last); 99 p.setRight(first);100 first.setLeft(p);101 last = p;102 count++;103 }104 }105 106 public void delete(People p){107 if(count <= 0){108 System.out.println("已經沒有人!");109 return;110 }else if(count == 1){111 first = last = null;112 count--;113 }else{114 p.getLeft().setRight(p.getRight());115 p.getRight().setLeft(p.getLeft());116 117 if(p == first){118 first = p.getRight();119 }else if (p == last){120 last = p.getLeft();121 }122 count--;123 }124 }125 }
4.運行結果:
Java-資料結構與演算法-逢3減1-物件導向