约瑟夫问题(链表)
我照着答案打了一遍代码,没跑出来,有没有眼神好的鱼油{:10_266:}第一段是答案,第二段是我打的,指出哪里不一样就行{:10_254:}
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
node *create(int n);
node *create(int n)
{
node *p = NULL, *head;
head = (node *)malloc(sizeof(node));
p = head;
node *s;
int i = 1;
if (0 != n)
{
while (i <= n)
{
s = (node *)malloc(sizeof(node));
s->data = i++; // 为循环链表初始化,第一个结点为1,第二个结点为2。
p->next = s;
p = s;
}
s->next = head->next;
}
free(head);
return s->next;
}
int main(void)
{
int n = 41;
int m = 3;
int i;
node *p = create(n);
node *temp;
m %= n; // m在这里是等于2
while (p != p->next)
{
for (i = 1; i < m - 1; i++)
{
p = p->next;
}
printf("%d->", p->next->data);
temp = p->next; //删除第m个节点
p->next = temp->next;
free(temp);
p = p->next;
}
printf("%d\n", p->data);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
node *create(int n);
node *create(int n)
{
node *p = NULL, *head;
head = (node*)malloc(sizeof(node));
p = head;
node *s;
int i = 1;
if (n != 0)
{
while (i <= n)
{
s = (node *)malloc(sizeof(node));
s->data = i++;
s->next = s;
p = s;
}
s->next = head->next;
}
free(head);
return s->next;
}
int main()
{
int n = 41;
int m = 3;
int i;
node *p = create(n);
node *temp;
m %= n;
while (p != p->next)
{
for (i = 1; i < m - 1; i++)
{
p = p->next;
}
printf("%d->", p->next->data);
temp = p->next;
p->next = temp->next;
free(temp);
p = p->next;
}
printf("%d\n", p->data);
return 0;
}
26行不一样
楼上说的对 万千只cnm 发表于 2021-8-12 19:59
楼上说的对
{:10_266:}你说楼上说得对说得对 焦糖橙子 发表于 2021-8-12 21:04
你说楼上说得对说得对
你说他说我说的对说得对{:10_285:}
页:
[1]