伙计们,我是队列的新手,很难理解它们是如何工作的。我所了解的是队列Append
的项目和Serve
附加的第一个项目。
从下面的代码中,我理解的是每次附加时,Link
总是NULL
,对吗?还有什么时候Tail !=NULL
成真?我很困惑,因为每次我们追加Tail
都设置为NULL
...
int item;
struct Node
{
int Data;
struct Node *Link;
};
typedef struct Node *QueuePointer;
void Append(QueuePointer &Head,QueuePointer &Tail, int Num)
{
QueuePointer NewNode;
NewNode= (QueuePointer)malloc(sizeof(struct Node));
NewNode->Data = Num;
NewNode->Link = NULL;
if(Tail == NULL)
{
Head = NewNode;
// printf("Queue is empty"); //checks if queue is empty
// printf("\n");
}
else
{
Tail->Link = NewNode;
}
Tail = NewNode;
printf("Inserted number %d \n", item); //checks if Appends into Queue working
}
void Serve(QueuePointer &Head, QueuePointer &Tail, int item)
{
QueuePointer Temp;
printf("Served ");
while(Head != NULL)
{
item = Head->Data;
Temp = Head;
Head = Head->Link;
if(Head == NULL)
{
Tail = NULL;
}
free(Temp);
printf("%d ", item); //prints out SERVED
}
}
int main()
{
QueuePointer Head, Tail;
Head = NULL;
Tail = NULL;
item = 1;
for (item = 1; item <= 4; item++)
{
// if(item%2==0)
// {
Append(Head, Tail, item); //Appends For Every Even Number Detected
// }
}
Serve(Head, Tail, item); //Calls out Serve Function, See LOOPING, please refer serve function
//****NOTE: the loop for Removing items is inside Serve Function
getch();
}