2017-03-09 8 views
1

이 프로그램은 사용자 데이터를 문자열 형태로 가져 와서 링크 된 목록에 넣어야합니다. 지금은 연결된 목록에 데이터를 가져올 수 있지만 인쇄되지 않는 이유는 확실하지 않습니다.링크 된 목록 항목이 인쇄되지 않음

#include<stdio.h> 
#include<stdlib.h> 

// define the node of the stack 
typedef struct node{ 
    char name[100]; 
    struct node *next; 
}Node, *NodePtr; 

// define the stack based on the linked list of nodes 
typedef struct{ 
    NodePtr top; 
}StackType,*Stack; 

// implement all the stack operations 
Stack initStack(){ 
    // allocate memory 
    Stack sp=(Stack)malloc(sizeof(StackType)); 
    // set the top pointer to NULL 
    sp->top=NULL; 
    return sp; 
} 

int empty(Stack s){ 
    return (s->top==NULL); 
} 


void push(Stack s, char *n){ 
    NodePtr np= (NodePtr) malloc(sizeof(Node)); 
    strcpy(np->name,n); 
    np->next=s->top; 
    s->top=np; 
} 

어디 선가 팝업 기능에 문제가 있다고 생각하지만, 이후의 기능을 종료하기 때문에 캔트

// pop the top element from the stack 
char* pop(Stack s){ 
    if(empty(s)){ 
     printf("\n Error: Stack is empty"); 
     return("err"); 
    } 
    char hold[100]; 
    strcpy(hold,s->top->name); 
    NodePtr temp=s->top; 
    s->top=s->top->next; 
    free(temp); 
    return hold; 
} 


int main(){ 
    char n[100]; 
    // create the stack 
    Stack s=initStack(); 

    printf("Enter a list of names\n"); 
    scanf("%s",&n); 
    while(strcmp(n,"end")!=0){ 
     push(s,n); 
     scanf("%s",&n); 
    } 

    // print the stack 
    while(!empty(s)) 
     printf("%s \n ", pop(s)); 

} 
+0

과 같이 호출 첫 번째 목록에? –

+0

어쨌든 실제로 무엇을 보나요? 컴파일 오류? 런타임 에러? 잘못된 출력입니까? 세부 사항을 제공하십시오. –

+2

'char hold [100];'은 지역 자동 변수입니다. 범위 외부에서 사용할 수 없습니다. – BLUEPIXY

답변

1

무효가 로컬 배열에 대한 포인터를 반환 pop 기능을 알아낼 것처럼 보이는 배열이 살아 있지 않습니다.

또한 pop 함수가 일부 메시지를 출력 할 때 나쁜 생각입니다.

그냥 기능을 다음과 같은 방법

int pop(Stack s, char *item) 
{ 
    int success = !empty(s); 

    if (success) 
    { 
     strcpy(item, s->top->name); 

     NodePtr temp = s->top; 
     s->top = s->top->next; 
     free(temp); 
    } 

    return success; 
} 

를 다시 작성하고 당신이에 데이터를 가지고 확실하게 무엇을 다음 목록 항목을 인쇄 관리 할 수없는 경우

while (pop(s, n)) 
{ 
    puts(n); 
}