首页 | 编程语言 | 网站建设 | 游戏天堂 | 冲浪宝典 | 网络安全 | 操作系统 | 软件时空 | 硬件指南 | 病毒相关 | IT 认证
软讯网络 > 编程语言 > C/C++ > 猫吃老鼠问题的链表实现
【标  题】:猫吃老鼠问题的链表实现
【关键字】:
【来  源】:http://blog.csdn.net/lizuonan/archive/2007/04/12/1561977.aspx

猫吃老鼠问题的链表实现

 一、问题描述
    现有n个老鼠围成一圆圈,有一只猫从任意位置开始吃老鼠,每次都隔一个老鼠吃,请给出最后一个老鼠的编号?题目要求是任给老鼠数n,输出猫最后吃的老鼠的编号。
二、代码

#include <iostream.h>

typedef struct _Node
{
    int num;
    _Node* pNext;
}Node, *pNode;

void InitLink(int n, pNode pHead);

void main()
{
    int n;
    int k;
    int num;
    pNode pHead = new Node;
    cout<<"输入老鼠的总数:";
    cin>>n;
    cout<<"输入起始数字:";
    cin>>k;
    if (k > n)
    {
        cout<<"请重新输入:";
        cin>>k;
    }
    InitLink(n, pHead);
    pNode p=pHead;
    pNode q;
    for (int i=0; i<(k-2+n)%n; i++)
    {
        p = p->pNext;
    }
    while (pHead->pNext != NULL)
    {
        if (p->pNext == p)
        {
            cout<<"The result is: "<<p->num<<endl;
            return;
        }
        p = p->pNext;
        q = p->pNext;
        num = q->num;
        p->pNext = q->pNext;
        if (pHead->pNext == q)
        {
            pHead->pNext = p->pNext;
        }
        delete q;
    }
}

void InitLink(int n, pNode pHead)
{
    pNode tail = new Node;
    tail->num = n;
    pNode q = tail;
    pNode p = NULL;
    for (int i=0; i<n-1; i++)
    {
        p = new Node;
        p->num = n-1-i;
        p->pNext = q;
        q = p;
    }
    tail->pNext = p;
    pHead->pNext = p;
}
判断GPRS是否连接的代码:【上一篇】
龙芯软件开发(36)- USB协议深入分析 返回设备描述符:【下一篇】
【相关文章】
没有相关文章
【随机文章】
  • smarty实例教程-模板设计篇-1
  • Windows Server 2003核心技术
  • 高性价比的IDC网络——层次化模型
  • SUN CLUSTER 3.0中NAFO组的概念和常用配置
  • Visual C++/MFC入门教程
  • pSeries 570机器主板上都集成哪些部件和接口?
  • book information address
  • Sharing session context between parent and external windows running on same host
  • XSS测试语句大全
  • ISA 2000 学习笔记(11)
  • 【相关评论】
    没有相关评论
    【发表评论】
    姓名:
    邮件:
    随机码*
    评论*
          
    |  首 页  |  版权声明  |  联系我们   |  网站地图  |
    CopyRight © 2004-2007 软讯网络 All Rigths Reserved.