2015-04-06 48 views
1

我通过代码排在队列中插入元素的逻辑,但我无法理解如何显示功能工作无法理解排队功能

void enqueue(int x) 
{ 
    queue *ptr; 
    queue *ptr1; 
    ptr=(queue*)malloc(sizeof(queue)); 
    ptr->info=x; 
    if(front==rear&&front==NULL) 
    { 
     ptr->next=NULL; 
     front=rear=ptr; 
    } 
    else 
    { 
    while(rear->next!=NULL) 
    { 
     rear=rear->next; 
    } 
    rear->next=ptr; 
    ptr->next=NULL; 
    } 
} 

//由于有前面之间没有任何联系及后,我无法理解如何旁边前面指向下一个元素在队列

void show() 
{ 
    queue *ptr=front; 
    while(ptr!=NULL) 
    { 
    printf("%d\n",ptr->info); 
    ptr=ptr->next; 
    } 
} 

回答

0

有前部和后部之间没有联系

当然有 - 这里是它是如何建立的:

if(front==rear&&front==NULL) 
{ 
    ptr->next=NULL; 
    front=rear=ptr; 
} 

front指向第一个插入的元素。最初,rear也指向相同的元素。当您向队列添加更多元素时,rear继续前进,而front仍然指向相同的初始元素。

show()需要该元素,并用它遍历链表。

请注意,如果项目总是使用insert插入,则while循环是不必要的,因为rear->next!=NULL始终为“false”。

+0

但是,在我已指定前置式>下将指向后方 – Newbie786 2015-04-06 10:13:22

+0

@ Newbie786在第二呼叫开始到插入'()','front'和'rear'指向相同的元件。当你在'rear-> next'插入一个元素时,'front-> next'也指向相同的元素,因为'front == rear'。 – dasblinkenlight 2015-04-06 10:38:46

+0

好吧,现在我得到它 – Newbie786 2015-04-06 11:06:17

0

这是你的代码,我正在评论你的代码在做什么。

void enqueue(int x) 
{ 
    queue *ptr; 
    queue *ptr1; 
    ptr=(queue*)malloc(sizeof(queue)); // allocating memory 
    ptr->info=x; // x is the value you are passing to ptr. 
    if(front==rear&&front==NULL) //this work for the first time when list is empty 
    { 
     ptr->next=NULL; //setting next location to null 
     front=rear=ptr; //till now only once value is there in the list so front=rear (both will be same) = ptr 
    } 
    else 
    { 
     while(rear->next!=NULL) // while loop will run until end of the list reached 
     { 
      rear=rear->next;  // moving to next location 
     } 

    rear->next=ptr;  // after getting last location assign it to rear->next 
    ptr->next=NULL; // again make next loation null. 
    } 
} 
+0

但如何显示功能正在工作,因为前后没有链接 – Newbie786 2015-04-06 10:18:33