撰寫一個程式,任意輸入n個100以內的數,將它們的奇數和偶數分別存入鏈隊為Q1和Q2中,然后配對輸出鏈隊Q1、Q2中的值,直到任一佇列為空為止。
輸入:
20
42 38 45 64 90 85 39 34 99 78 19 83 75 70 79 88 61 88 54 80
輸出:
45 42
85 38
39 64
99 90
19 34
83 78
75 70
79 88
61 88
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
typedef struct node *PNODE;
typedef struct
{
PNODE front,rear;
}Linkqueue;
void initqueue(Linkqueue *q)
{
q->front = q->rear = (PNODE)malloc(sizeof(NODE));
if(!q->front)
exit(0);
q->front->next = NULL;
}
Linkqueue insertqueue1(Linkqueue *q, int n)
{
int i;
PNODE p;
p = (PNODE)malloc(sizeof(NODE));
if(p==NULL)
exit(0);
for(i=0;i<n;i++)
{
scanf("%d",&p->data);
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
}
Linkqueue insertqueue2(Linkqueue *q, int x)
{
int i;
PNODE p;
p = (PNODE)malloc(sizeof(NODE));
if(p==NULL)
exit(0);
x = p->data;
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
void outqueue(Linkqueue *q,int n)
{
int x,i;
PNODE p;
if(q->front==q->rear)
return;
for(i=0;i<n;i++)
{
p = q->front->next;
x = p->data;
q->front->next = p->next;
if(q->rear==p)
q->rear = q->front;
free(p);
}
}
Linkqueue panduan(Linkqueue *q)
{
PNODE p;
Linkqueue *q1;
Linkqueue *q2;
initqueue(q1);
initqueue(q2);
p = q->front->next;
while(q->front!=q->rear)
{
if(p->data%2==0)
{
insertqueue2(q1, p->data);
}
else
{
insertqueue2(q2, p->data);
}
p = p->next;
}
PNODE p1,p2;
p1 = q1->front->next;
p2 = q2->front->next;
while(q1->front!=q1->rear&&q2->front!=q2->rear)
{
printf("%d %d\n",p1->data,p2->data);
p1 = p1->next;
p2 = p2->next;
if(q1->rear==p1&&q2->rear==p2)
{
q1->rear = q1->front;
q2->rear = q2->front;
}
free(p1);
free(p2);
}
}
int main()
{
Linkqueue q;
int n;
scanf("%d",&n);
initqueue(&q);
insertqueue1(&q,n);
panduan(&q);
return 0;
}
這個代碼問題出在哪里呢?得不出結果啊
麻煩大佬們使用佇列作答
另外程式在panduan()這個函式時,我除錯它顯示program received signal SIGSEGV
uj5u.com熱心網友回復:
沒有人在嗎?·
uj5u.com熱心網友回復:
Linkqueue insertqueue1(Linkqueue *q, int n){
int i;
PNODE p;
p = (PNODE)malloc(sizeof(NODE));
if(p==NULL)
exit(0);
for(i=0;i<n;i++)
{ //你這里是要插入n個數字,但是你每個給每一要插入佇列的節點分配記憶體
// 要把前面對p對malloc,拉到這個回圈里面來
scanf("%d",&p->data);
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
}
先改了這個再看吧
uj5u.com熱心網友回復:
要插入n個數字,就要malloc呼叫n次, 每次申請一個新的節點,把它插入進去才對uj5u.com熱心網友回復:
我更改了,但還是有問題,除錯顯示在執行panduan這個函式時,initqueue(q1)這一步的q->front = q->rear = (PNODE)malloc(sizeof(NODE))顯示program received signal SIGSEGV,不是很明白啊,求教。
uj5u.com熱心網友回復:
uj5u.com熱心網友回復:
求救啊
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/71318.html
標籤:C語言
