首页 > 代码库 > 循环链表(隔M杀1)
循环链表(隔M杀1)
<!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>
循环链表(隔M杀1)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。