uva133-救济金发放

此题为小白书里数据结构基础关于线性表的题目

 

翻译请戳 http://luckycat.kshs.kh.edu.tw/

 

解题思路

当时直接用动态的双向链表模拟了。。。

但是用双向链表很纠结啊,如果你加入头结点之后的查找会变得很麻烦,

如果不加头结点的话,插入节点会很麻烦。。。

但已经写了就不想改了。。。如果你用静态链表实现亦可以,看个人喜好。

注意 如果有头结点,一开始从头结点数起,第一次删除后,以后的删除都要忽略头结点(跳过不计)。

 

代码:

#include<iostream>
#include<stdio.h> 
using namespace std;
typedef struct node {
    int id;
    struct node *pre, *next;
}pesNode;
void Insert(pesNode *first, pesNode *s)
{
    pesNode *p = first;
    while(p->next != first) p = p->next;
    s->next = p->next;
    p->next->pre = s;
    p->next = s;
    s->pre = p;
}
void Delete(pesNode *p)
{
    p->pre->next = p->next;
    p->next->pre = p->pre;
    delete p;
}
int main()
{
    int n, k, m;
    while(scanf("%d%d%d", &n, &k, &m) && n!=0&&k!=0&&m!=0) {
        pesNode *first = new pesNode;
        first->id = 0;
        first->next = first; first->pre = first;
        for(int i=1; i<=n; i++) {
            pesNode *s = new pesNode;
            s->id = i;
            Insert(first, s);
        }
        pesNode *p, *q;
        p = first; q = first;
        int tot = n;
        while(tot) {
            int i = 0;
            while(i != k) {if(p->next != first){p=p->next;i++;}else p=p->next;}
            int j = 0;
            while(j != m) {if(q->pre != first){q=q->pre;j++;}else q=q->pre;}
            pesNode *tempP = p;
            pesNode *tempQ = q;
            if(p->pre == q){p = p->pre->pre;q = q->next->next;}
            else {p=p->pre;q = q->next;}
            if(tempP->id == tempQ->id) {
                if(tempP->next == first && tempP->pre == first) { printf("%3d\n", tempP->id);break; }
                else printf("%3d,", tempP->id);
                tot--;
            }
            else {
                if(tempP->pre==first && tempQ->next == first && tempP->next == tempQ|| 
                    tempP->next==first && tempQ->pre==first && tempQ->next == tempP)
                    {printf("%3d%3d\n", tempP->id, tempQ->id); break; }
                else printf("%3d%3d,", tempP->id, tempQ->id);
                tot -= 2;
            }
            if(tempP!=tempQ) {Delete(tempP);Delete(tempQ);}
            else Delete(tempP);
        }
    }
}

 

转载于:https://www.cnblogs.com/ZengWangli/p/5747711.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值