2013-05-31 137 views
0

我尝试了第一次实现队列。它显示先输入的数据和最后输入的数据。以下是我的代码。如果你能找到任何错误,请帮助我。队列刚刚弹出第一个和最后一个元素

#include <windows.h> 
#include "stdafx.h" 
#include "iostream" 
#include<stdio.h> 
#include<conio.h> 
#include<stdlib.h> 

struct node 
{ 
    int rollno; 
    struct node*n; 
}; 

void read(struct node*); 
void display(struct node*); 
struct node* create(); 
struct node* cread(); 
struct node*head = NULL; 
struct node*tail = NULL; 

void read(struct node*p) 
{ 
    scanf("%d",&p->rollno); 
    p->n=NULL; 
    printf("\n"); 
} 

void display(struct node*p) 
{ 
    printf("%d\n",p->rollno); 
} 

struct node* create() 
{ 
    struct node*q; 
    q=(struct node*)malloc(sizeof(struct node)); 
    return q; 
} 

struct node* cread() 
{ 
    struct node*j; 
    j=create(); 
    read(j); 
    return j; 
} 

void push(struct node*cur) 
{ 
    if(head==NULL) 
    { 
     head=cur; 
     tail=cur; 
    } 
    else 
    { 
     struct node*f; 
     //f=head; 
     //cur->n=f; 
     //head=cur; 
     head->n=cur; 
    } 
} 

void pop_all() 
{ 
    struct node*p; 
    p=head; 
    if(head==NULL) 
    {printf("\n\t\t\tQUEUE EMPTY\n");} 
    else 
    { 
     head = tail; 
     while(head!=NULL) 
     { 
      display(head); 
      p=head; 
      head = head->n; 
      //tail = tail->n; 
      //head=tail; 
      //free(p); 
     } 

     while(head!=NULL) 
     { 
      display(head); 
      p=head; 
      head = head->n; 
      //tail = tail->n; 
      //head=tail; 
      //free(p); 
     } 
    } 
} 

void main() 
{ 
    struct node*cur; 
    int a,q; 
    char ch; 
    while(1) 
    { 
     printf("Press 1 For PUSH\n"); 
     printf("Press 2 For POP ALL\n"); 
     printf("Press 3 For EXIT\n"); 
     scanf("%d",&a); 
     if(a==1) 
     { 
      cur=cread(); 
      push(cur); 
     } 

     else if(a==2) 
     { 
      pop_all(); 
     } 
     else if(a==3) 
     { 
      break; 
     } 

     printf("Press Any Key To Clear Screen\n"); 
     ch=getch(); 
     system("cls"); 
    } 
} 

回答

1

有一些问题。

  1. 当链接除第一个元素之外的所有元素时,代码缺失。您需要将前一个元素的下一个指针设置为新元素。
  2. Don't cast the return value of malloc() in C
  3. tail变量似乎没有被使用,所以它可以被删除。
相关问题