首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

入队和出队实现有关问题,如何会出现段异常

2012-09-11 
入队和出队实现问题,怎么会出现段错误C/C++ code#include iostream#include stdio.h#include string

入队和出队实现问题,怎么会出现段错误

C/C++ code
#include <iostream>
#include <stdio.h>
#include <string>
#include <stdlib.h>

using namespace std;
   
typedef struct node{
  int data;
  struct node *next;
} node;
typedef struct queue{
  node *first,*rear;//队头 队尾
} queue;
//入队
queue *insert(queue *q,int x)
{
  printf("%d",x);// 主函数里调用了为什么这句没有执行 ???
  node *t;
  t=(node *)malloc(sizeof(node));
  t->data=x;
  t->next=NULL;
  if(q->rear==NULL )
  {  
  q->first=t;
  q->rear=t;
  }
  else
  {  
  q->rear->next=t;
  q->rear=t;

  }  
  return q;  
 }  
 //出队  
 queue *del(queue *q)  
 {  
  node *p=q->first;  
  if( q->first==NULL )  
  {  
  printf("溢出\n");  
  }  
  else  
  {  
  if( q->first==q->rear )  
  {  
  q->first=NULL;  
  q->rear=NULL;  
  }  
  else  
  {  
  q->first=q->first->next;  
  free(p);  
  }  
  }  
  return q;  
 }  
   
 void print(queue *q)  
 {  
  node *p=q->first;  
  while(p->next!=NULL )  

  }  
}  
   
int main()  
{  
  queue *aa=(queue*)malloc(sizeof(queue));  
  aa->first==NULL;  
  aa->rear==NULL;  
  aa=insert(aa,21);  
  print(aa);  
  printf("\n");  
   
  aa=del(aa);  
  print(aa);  
  printf("\n");  
   
  return 0;  
}  

[/code]


[解决办法]
1. main中
 aa->first==NULL;
aa->rear==NULL;
改为
aa->first=NULL;
aa->rear=NULL; 
2. print中
 while(p->next!=NULL ) 改为
 while(p&&p->next!=NULL )并且循环内没有代码,一旦进入就没法退出,因添加类似
p = p->next;
3. deque后没有释放内存,自己改吧。
[解决办法]
不断错误才怪呢!
int main()
{
queue *aa=(queue*)malloc(sizeof(queue));
aa->first==NULL;
aa->rear==NULL;
赋值应该用 ‘=’。
另外你的print函数似乎没写完

热点排行