循环链表
传说在公元1 世纪的犹太战争中,犹太历史学家弗拉维奥·约瑟夫斯和他的40 个同胞被罗马士兵包围。犹太士兵决定宁可自杀也不做俘虏,于是商量出了一个自杀方案。他们围成一个圈,从一个人开始,数到第三个人时将第三个人杀死,然后再数,直到杀光所有人。约瑟夫和另外一个人决定不参加这个疯狂的游戏,他们快速地计算出了两个位置,站在那里得以幸存。写一段程序将n 个人围成一圈,并且第m 个人会被杀掉,计算一圈人中哪两个人最后会存活。使用循环链表解决该问题。
1 function node(value){ 2 this.value = value; 3 this.next = null; 4 } 5 function list(){ 6 this.head = new node(1); //默认链表中包含一个头节点 7 this.remove = remove; 8 this.insert = insert; 9 this.before = before; 10 this.back = back; 11 this.find = find; 12 this.display = display; 13 this.length = length; 14 } 15 16 function length(){ 17 var current = this.head; 18 var k = 1; 19 while(current.next != null && current.next != this.head){ 20 current = current.next; 21 k++; 22 } 23 return k; 24 } 25 26 function insert(n){ 27 for(var i =2;i<=n+1;i++){ 28 var newnode = new node(i); 29 var forenode = this.find(i-1); 30 forenode.next = newnode; 31 newnode.next = this.find(1); 32 } 33 } 34 35 function remove(m,k){ 36 while(this.length()>2){ 37 var kill = this.back(m,k); 38 var beforenode = this.before(kill); 39 if(kill == this.head){ 40 this.head = kill.next; 41 } 42 beforenode.next = kill.next; 43 kill.next = null; 44 person = this.remove(beforenode.next.value,k); 45 } 46 return person; 47 } 48 49 function before(elem){ 50 var current = this.head; 51 while(current.next != null && current.next != this.head && current.next != elem){ 52 current = current.next; 53 } 54 return current; 55 } 56 57 function back(k,m){ 58 var now = this.find(k); 59 while(m>1){ 60 now = now.next; 61 m--; 62 } 63 return now; 64 } 65 66 function display() { 67 var currNode = this.head; 68 while (currNode.next != null && currNode.next != this.head) { 69 console.log(currNode.value); 70 currNode = currNode.next; 71 } 72 console.log(currNode.value); 73 } 74 75 function find(elem){ 76 var current = this.head; 77 while(current.next != null && current.next != this.head && current.value != elem){ 78 current = current.next; 79 } 80 return current; 81 } 82 83 var person = new list();
person.insert(); //再插入 m-1个节点
person.remove(i,j); //从第i个开始,杀掉第j个人