当我尝试使用我实现为链接列表的Priority Queue类时,我发现我的指针一直指向彼此。我在网上找到的这个简单队列实现中修改了它:http://ben-bai.blogspot.com/2012/04/simple-queue-data-structure-in-ansi-c.html
这是我的队列和节点结构:
typedef struct Node
{
Instruction pointer;
struct Node *next;
} Node;
typedef struct Queue
{
Node *head;
Node *tail;
void (*push) (struct Queue *, Instruction);
Instruction (*pop) (struct Queue *);
Instruction (*peek) (struct Queue *);
Instruction (*removeNode) (struct Queue *, Instruction);
int size;
} Queue;
指令是指向我实现的另一个名为Command的结构的指针。 这是我的推送和流行方法:
void
push (Queue * queue, Instruction instr)
{
Node *n = (Node *) malloc (sizeof (Node));
n->pointer = instr;
n->next = NULL;
if (queue->head == NULL
|| n->pointer->priority > queue->head->pointer->priority)
{
n->next = queue->head;
queue->head = n;
queue->size++;
}
else
{
Node *temp = queue->head;
Node *p = temp->next;
while (p != NULL)
{
if (p->pointer->priority < n->pointer->priority)
{
n->next = p;
temp->next = n;
queue->size++;
return;
}
p = p->next;
temp = temp->next;
}
n->next = NULL;
temp->next = n;
queue->size++;
}
}
Instruction
pop (Queue * queue)
{
Node *head = queue->head;
Instruction node = head->pointer;
queue->head = head->next;
queue->size--;
free (head);
return node;
}
这是我用来遍历LL的while循环,只是打印节点的值和它们指向的指令:
Node *n = ready.head;
while (n != NULL)
{
puts ("right here now");
printNode (n->pointer);
n = n->next;
}
这将打印出来 说明2 说明3 说明2 说明3 说明3 等等,无休止地。
提前感谢您的帮助