此代码目前的目的是创建一个循环的双向链接列表,该列表显示囚犯编号,稍后我将在删除函数中应用约瑟夫斯问题
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* prev;
struct Node* next;
};
struct Node* first, *last; // global variables first and last
struct Node* GetNewNode(int x)
{
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = x;
newNode->next = newNode->prev = newNode;
first = newNode;
return newNode;
};
我认为我的打印或插入功能有问题
void insertEnd(int x)
{
struct Node* newNode = GetNewNode(x);
struct Node* temp = GetNewNode(x);
if (first == NULL)
{
first = newNode;
return;
}
last = first->prev;
temp->data = x;
temp->next = first;
first->prev = temp;
temp->prev = last;
last->next = temp;
}
此功能无法打印我希望在主for循环中打印的五个节点
void printList()
{
struct Node* temp = first;
while(temp->next != first)
{
下面的行从不打印。
printf("prisoner %d| ", temp->data);
temp = temp->next;
}
printf("%d", temp->data);
}
int main()
{
int n,k;
printf("How many prisoners are there: ");
scanf("%d", &n);
此for循环正在尝试为列表中添加的每个节点分配囚犯编号
for(int i = 1; i <= n; i++)
{
insertEnd(i);
}
printList();
return 0;
}