链表练习:约瑟夫环
2013-10-09 19:55
197 查看
链表练习:约瑟夫环(VC下调试成功)
Mark:以前一直是用数组进行模拟的,今天刚学链表,于是就写了一个简易版的..................
#include <stdio.h>
#include <stdlib.h>
typedef struct node *link;
struct node
{
unsigned char item;
link next;
};
static link head = NULL;
link make_node(unsigned char item)
{
link p = (struct node *)malloc(sizeof(*p));
p ->item = item;
p ->next = NULL;
return p;
}
void insert(link p)
{
p ->next = head;
head = p;
}
void traverse(void (*visit)(link))
{
link p;
for(p = head; p; p = p ->next)
visit(p);
}
void print_item(link p)
{
printf("%d\n",p ->item);
}
int main(void)
{
int i,m;
link p = NULL;
for(i = 10; i > 0; i--)
{
p = make_node(i);
insert(p);
}
for(p = head; p ->next; p = p ->next);
p ->next = head;
//环形链表
// traverse(print_item);
printf("Please input the number you want to kick out:\n");
scanf("%d",&m);
p = head;
link q = NULL;
printf("The kick out order was:\n");
while(p ->next != p)
{
for(i = 1; i < m - 1; i++)
{
p = p ->next;
}
q = p ->next;
p ->next = q ->next;
printf("%d ",q ->item);
free(q);
p = p ->next;
}
printf("\n");
printf("The last one was:\n");
printf("%d\n",p ->item);
free(p);
head = NULL;
return 0;
}
Mark:以前一直是用数组进行模拟的,今天刚学链表,于是就写了一个简易版的..................
#include <stdio.h>
#include <stdlib.h>
typedef struct node *link;
struct node
{
unsigned char item;
link next;
};
static link head = NULL;
link make_node(unsigned char item)
{
link p = (struct node *)malloc(sizeof(*p));
p ->item = item;
p ->next = NULL;
return p;
}
void insert(link p)
{
p ->next = head;
head = p;
}
void traverse(void (*visit)(link))
{
link p;
for(p = head; p; p = p ->next)
visit(p);
}
void print_item(link p)
{
printf("%d\n",p ->item);
}
int main(void)
{
int i,m;
link p = NULL;
for(i = 10; i > 0; i--)
{
p = make_node(i);
insert(p);
}
for(p = head; p ->next; p = p ->next);
p ->next = head;
//环形链表
// traverse(print_item);
printf("Please input the number you want to kick out:\n");
scanf("%d",&m);
p = head;
link q = NULL;
printf("The kick out order was:\n");
while(p ->next != p)
{
for(i = 1; i < m - 1; i++)
{
p = p ->next;
}
q = p ->next;
p ->next = q ->next;
printf("%d ",q ->item);
free(q);
p = p ->next;
}
printf("\n");
printf("The last one was:\n");
printf("%d\n",p ->item);
free(p);
head = NULL;
return 0;
}
相关文章推荐
- 算法练习-单链表约瑟夫环的O(n)算法
- 课堂练习之链表节点删除与构建堆
- “用最小堆将k个已排序链表合并为一个排序链表”(算法导论 练习6.5-9)
- 约瑟夫环之循环链表实现
- Windows驱动开发小练习-内存分配与链表操作
- 数据结构练习——简单单链表
- 链表解决约瑟夫环问题
- C链表练习时对指针的深刻理解
- 链表的综合练习:增、删、改、查
- 数据结构 循环链表的应用:约瑟夫环问题
- 2015年大一下第12周项目4-链表类(2)约瑟夫环
- 约瑟夫环——静态循环链表,动态循环链表
- 【单链表经典面试题解析四】用单链表实现约瑟夫环
- C/C++链表练习时遇到的问题
- 链表练习:多项式的加法和乘法
- 今天主要学习的是 链表,单链,循环链表和双向链表,总体感觉还可以,还是有点懵懵的,需要勤加练习。
- 约瑟夫环-单向循环链表
- 简单链表练习
- LintCode入门练习——466. 链表节点计数
- 数据结构练习1——链表合并