2014-02-26 5 views
0

"코드는 struct에 int 데이터 유형이 있지만 struct의 char 데이터 유형에는 작동하지 않는 경우 작동합니다."C 대기열 구현의 데이터 유형

#include <stdio.h>  
#include <stdlib.h> 
#define null 0 

struct node{ 
     char data;//works fine if it is int data 
     struct node *next; 
     }; 

void push(struct node **head)//add element to the queue 
{ 
struct node *newnode,*p,*q; 
char d; 
newnode=(struct node *)malloc(sizeof(struct node)); 
printf("\nenter the data you want to insert:"); 
scanf("%c",&d); 
newnode->data=d; 
if(*head!=null) 
{ 
    p=*head; 
    while(p!=null) 
    { 
     q=p; 
     p=p->next; 
    } 
    q->next=newnode; 
    newnode->next=p; 
} 
else 
    *head=newnode; 
printf("the data is %c\n",newnode->data); 
    } 

void pop(struct node **head)//pops element of the queue 
{ 
struct node *p; 
if(*head!=null) 
{ 
    p=*head; 
    *head=p->next; 
    printf("The data popped is %c \n",p->data); 
    free(p); 
} 
else 
    printf("no data to pop\n"); 
} 

void traverse(struct node **head)//displays the queue 
{ 
struct node *k; 
if(*head!=null) 
{ 
    k=*head; 
    printf("\nthe data of the queue is:\n"); 
    while(k!=0) 
    { 
     printf("%c\n",k->data); 
     k=k->next; 
    } 
} 
else 
    printf("no data\n"); 
    } 

void main() 
{ 
struct node *head=null; 
int i,n; 
printf("how many data you want to enter\n"); 
scanf("%d",&n); 
for(i=0;i<n;i++) 
{ 
    push(&head); 
} 
traverse(&head); 
pop(&head); 
traverse(&head); 
} 

출력 : 데이터가

이를 입력입니다 : 당신이 삽입 할

3

가 데이터를 입력

입력하려면 얼마나 많은 데이터 ./queue

삽입하려는 데이터 : 데이터는

입니다. (210)

가 삽입 할 데이터를 입력 데이터는 큐의

데이터입니다 : 팝

데이터는 큐의

데이터입니다

된다

"

+0

디버거 무엇을 말하는가 ? – pm100

+0

괜 찮 아 요 아무 문제 없어 .debugs 확인 – Paku

+0

질문이 모호하다 .. 좀 더 구체적으로 할 수 있겠습니까? – Prabesh

답변

1

이 유일한 문제 될 수 있지만하지 않을 수 있습니다 때 push 처음 ELEM 당신은 결코 newnode->next = null을 설정하지 마십시오.

큐에 \n, a (공백)으로 구성되어 있기 때문에 출력에 문제가 있습니다.

+0

\ n 및 공간이 어떻게 구성되어 있습니까? input.And newnode-> next = p는 제대로 작동하지 않습니다. – Paku

+0

scanf에 대한 대부분의 다른 형식 지정자와 달리,'% c'는 공백을 건너 뛰지 않습니다. 'newnode-> next = p'는 괜찮지 만 첫 번째 요소는 코드가'if' 문의'else' 부분을 선택하고'else' 부분은'newnode-> next'를 지정하지 않습니다 . –

1

입력 버퍼를 지워야합니다. 문제는 첫 번째 입력 (입력 수)을 누른 후 입력 (\ n)이 첫 번째 입력 문자로 읽히기 때문입니다.
입력 버퍼를 지우는 방법을 알고 싶다면 link을 읽어보십시오. 그것은 \ n 뒤에 오는 동일한 입력 문제를 해결합니다.

+0

예, 작동했습니다! 감사합니다 ... – Paku

1

빠른 수정 (안전성 무시 등)으로 pushf에서 scanf ("% c, &d)를 scanf ("\ n % c ", &d)로 변경할 수 있습니다. .는 정수 작업 이유 인 줄 바꿈을 제거합니다 scanf와의 정수 형식을 사용하여 개행 문자 및 추진하고자하는 실제 문자를 데리러

참조 :. scanf() leaves the new line char in buffer?

+0

예,이 기능도 작동합니다! – Paku