2012-07-19 212 views
0

我一直試圖通過鏈表來實現優先級隊列。但是,當我使用我在下面的程序中使用的add()函數時,我無法將數據添加到列表中。一些幫助會很棒!使用鏈表的優先級隊列

該程序要求我將各種數據分類到單獨的隊列中,同一隊列中的所有元素具有相同的優先級。

即:數據:A,優先級:1 數據:B,優先級:2 數據:C,優先級:1

那麼它應該存儲數據如下:

Q1:A, C Q2:B

我的程序如下。我想我搞亂了我發送的函數作爲參數添加的指針...

`#include<stdio.h> 
#include<conio.h> 
struct node{ 
    char data[3]; 
    struct node *next; 
    }; 
    void del(struct node *); 
    void add(struct node *,struct node **); 
    void display(struct node *); 
    int main() 
    { 
     int i; 
     struct node *list[5]; 
     struct node *q; 
     int pr,n; 
     for(i=0;i<5;i++) 
     list[i]=NULL; 
     printf("enter the no.of elements"); 
     scanf("%d",&n); 
     for(i=0;i<n;i++) 
     { 
         q=(struct node*)malloc(sizeof(struct node)); 
         printf("Enter data"); 
         scanf("%s",&(q->data)); 
         printf("\npriority :"); 
         scanf("%d",&pr); 
         pr--; 
         add(q,&list[pr]); 
     } 
     for(i=0;i<5;i++) 
     { 
         display(list[i]); 
     } 
     for(i=0;i<5;i++) 
         del(list[i]); 
         getch(); 
     return 0; 
     } 
     void add(struct node *q,struct node **n) 
     { 
      if(*n==NULL) 
      { 
         *n=q; 
         return; 
      } 
      while((*n)->next!=NULL) 
      *n=(*n)->next; 
      (*n)->next=q; 
      q->next=NULL; 
      return; 
     } 
     void del(struct node *q) 
     { 
      if(q==NULL) 
      { 
         printf("Queue empty"); 
         return; 
      } 
      while(q->next->next!=NULL) 
      q=q->next; 
      q->next=NULL; 
     } 
     void display(struct node *q) 
     { 
      while(q!=NULL) 
      { 
          printf("%s\t",q->data); 
          q=q->next; 
      } 
      printf("\n"); 
      return; 
     }` 

在此先感謝! :)

回答

0

函數「add」中的循環怎麼樣?

while((*n)->next!=NULL) *n=(*n)->next; 

你不是這個意思嗎?

while((*n)->next!=NULL) n=&(*n)->next; 
+0

由於一噸!我剛剛意識到這一點。 :) – Rahul 2012-07-19 11:21:39

0

幾個問題我看到:

  1. ,Q->接下來應該 「Q =(結構節點*)malloc的(的sizeof(結構節點))」 後設置爲空,否則,它可能是任何東西;
  2. 在del中,你實際上並沒有刪除任何東西(所有由「malloc」分配的資源應該由「free」釋放);
  3. 也德爾,「Q->下一個」可以爲空,所以「Q->下一步 - >下一步」可能崩潰的程序