《C算法》P67,3-8约瑟夫问题(循环链表求解)
关于建链表,起初我以为是这样的:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef struct node *link;
struct node
{
int item;
link next;
};
int n, m;
int main()
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
scanf("%d%d", &n, &m);
link p, t;
t = p = (link)malloc(sizeof(node)), p->item = 1, p->next = p;
for(int i = 2; i <= n; ++ i)
{
p->next = (p = (link)malloc(sizeof(node)));
p->item = i;
}
p->next = t;
p = t;
for(int i = 0; i < n; ++ i, p = p->next)
{
printf("%d ", p->item);
}
return 0;
}
n = 10时 出来的结果是这样的:
1 1 1 1 1 1 1 1 1 1
何解?
注意这行
p->next = (p = (link)malloc(sizeof(node)));
=是右赋值的
也就是说,首先p被赋值成新建的节点,然后这个新的p next指向本身
正确的做法是这样的:
for(int i = 2; i <= n; ++ i)
{
p = (p->next = (link)malloc(sizeof(node)));
p->item = i;
}
约瑟夫问题与循环链表
本文通过解决约瑟夫问题介绍了循环链表的构建方法,并对比了两种不同的链表构建过程,指出了其中的问题所在及正确实现方式。
555

被折叠的 条评论
为什么被折叠?



