33,311
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int num;
char name[20];
struct node *next;
};
struct node *create_singly_link(int num)
{
struct node*head, *prev, *cur;
int i;
head = NULL;
for(i = 0; i < num; i++) {
cur = (struct node *)malloc(sizeof(struct node));
if (!cur) {
printf("Malloc error!");
return NULL;
}
cur->next = NULL;
cur->num = i+1;
snprintf(cur->name, 20-1, "%c", 'A'+i);
if (!head) {
head = cur;
prev = cur;
} else {
prev->next = cur;
prev = prev->next;
}
}
prev->next = head;
return head;
}
static void test_print(struct node *phead)
{
struct node *pcur = phead->next;
printf("num = %d\t name = %s\n", phead->num, phead->name);
while (pcur != phead) {
printf("num = %2d\t name = %s\n", pcur->num, pcur->name);
pcur = pcur->next;
}
}
int output( struct node *head, int start, int step, int total)
{
struct node *p, *q;
int count = 0;
int num = 0, i;
q = head;
for(i = 0; i < start; i++)
q = q->next;
while(count < total-1) {
p = q->next;
num++;
if(!(num % step)) {
q->next = p->next;
printf("%s\n", p->name);
free(p);
count++;
} else {
q = p;
}
}
printf("num = %d\t, name = %s\n", q->num, q->name);
free(q);
return 0;
}
int main(int argc, const char *argv[])
{
int total, step, start;
struct node *head;
printf("Please input total test number: ");
scanf("%d", &total);
head = create_singly_link(total);
test_print(head);
printf("Please input start position and steps: ");
scanf("%d%d", &start, &step);
output(head, start, step, total);
return 0;
}
参考一下吧,你可以把结构体里定义的name去掉,只留
楼主的问题主要是出在Del函数里。