<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>隔m杀1</title> </head> <body> </body> </html> <script> (function(w){ function Person(ele){ this.ele = ele; this.next = null; } w.List = function(){ this.head = new Person(1); this.head.next = this.head; } List.prototype={ //插入item元素后面 insert:function(newPer,item){ var later = item.next; item.next = newPer; newPer.next= later; }, //查找元素 find:function(item){ var current = this.head; while(current.next !== this.head && current.next !== item){ current = current.next; } return current; }, //打印所有元素 print:function(){ var current =this.head; var str = current.ele; while(current.next !== this.head){ current = current.next; str += ","+current.ele; } document.write(str); }, //快速生成链表元素 add:function(m){ var temp; var count; if(m>1){ count = 2; temp = new Person(2); this.head.next =temp; while(++count <= m){ this.insert(new Person(count),temp); temp = temp.next; } temp.next = this.head; } }, //找到元素 find:function(item){ var current = this.head; while(current.ele !== item && current.next !== this.head){ current = current.next; } return current; }, //找到前一个 findpre:function(item){ var current = this.head; var pre; while(current.ele !== item && current.next !== this.head ){ pre = current; current = current.next; } return pre; }, //找到后面第几位 findLater:function(item,n){ var current = this.find(item); var count = 0; while(++count <= n){ current = current.next; } return current; }, //实时链表长度 len:function(){ var count=1; var current = this.head; while(current.next !== this.head){ count++; current = current.next; } return count; } } })(window) //任务:40人隔3杀1 function game(n,m){ var list = new List(); list.add(n); var del,pre; var current = list.head; while(list.len() >= m){ del = list.findLater(current.ele,m-1); if(del === list.head){ list.head = list.head.next; } pre = list.findpre(del.ele); pre.next = del.next; current = list.findLater(current.ele,m-1) } list.print(); } game(1000,3) </script>
时间: 2024-10-02 01:36:38