线性表的应用-选首领

N个游戏者围成一圈,从一个人开始报数1,2,3。数到3的人退出圈子,最后留在圈子里面的是首领

 

public   class  SelectCaptain  {
    
public static void main(String[] args) {
        CycleLinkList ll 
= new CycleLinkList();
        
for (int i = 0; i < 10; i++{
            ll.insert(
"i" + i);
        }

        ll.browse();
        System.out.println(
"///before play()");
        ll.play();
        System.out.println(
"///after play()");
        ll.browse();
    }

}


class  Node  {
    String data; 
// 数据

    Node next; 
// 指针

    Node(Node node) 
{
        
this.data = node.data;
        
this.next = node.next;
    }


    Node(String data) 
{
        
this.data = data;
        
this.next = null;
    }


    Node(String data, Node link) 
{
        
this.data = data;
        
this.next = link;
    }

}


class  CycleLinkList  {
    Node head;

    CycleLinkList() 
{
        head 
= new Node("head");
        head.next 
= head;
    }


    
void insert(String data) {
        Node t 
= new Node(data, head.next);
        head.next 
= t;
    }


    
boolean delete(String data) {
        Node t 
= head;
        
int count = 0;
        
for (;;) {
            
if (t.next == null{
                System.out.println(
"can not find");
                
return false;
            }

            
if (t.next.data.equals(data)) {
                
// 找到数据
                System.out.print("find it:" + data);
                System.out.println(
" t.next.next:" + t.next.next.data);
                t.next 
= t.next.next;
                
return true;
            }

            count
++;
            t 
= t.next;
        }

    }


    
public void browse() {
        Node t 
= new Node(head);
        
for (;;) {
            
if (t.next == head) {
                System.out.println(t.data 
+ "->end");
                
return;
            }


            System.out.print(t.data 
+ "->");
            t 
= t.next;
        }

    }


    
public void play() {
        Node t 
= new Node(head.next);
        
int count = 0;
        
int N = 10;
        
for (;;) {
            
if (count == 2{
                delete((t.data));
                browse();
                N
--;
            }

            
if (N == 1{
                System.out.println(
"captain is:" + t.data);
                
return;
            }

            t 
= t.next;
            count
++;
            
if (count > 2{
                count 
= 0;
            }

            
if (t == head) {
                t 
= t.next;
            }

        }

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值