标签:
此题为小白书里数据结构基础关于线性表的题目
翻译请戳 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); } } }
标签:
原文地址:http://www.cnblogs.com/ZengWangli/p/5747711.html