[問題] 關於堆疊的問題
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 )
( 未必需要依照此格式,文章條理清楚即可 )
遇到的問題: (題意請描述清楚)
我的堆疊,push進去時,應該沒有錯誤,但是在最後pop的地方,卻pop出都一模一樣
的數值!
希望得到的正確結果:
正確的pop出結果
程式跑出來的錯誤結果:
開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux)
Dev-C
有問題的code: (請善用置底文標色功能)
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
int main()
{
int i,j,k;
char* str2;
char str[512];
char buf[512];
struct stackTag *stack;
stack=stackCreate();
while(fgets(buf,512,stdin)!=NULL)
{
i=0;
k=0;
while(buf[i]!='\0')
{
j=0;
printf("dd\n");
system("PAUSE");
while(buf[i]!=' '&&buf[i]!='\0'&&buf[i]!='\n')
{
str[j++]=buf[i++];
printf("ff\n");
}
str[j]='\0';
i++;
stackPush(stack,str);
k++;
printf("%d th inside is %s and %s\n",k,(char*)stackGet(stack),str);
strcmp(str," ");
}
printf("outcome=================\n");
while(!stackEmpty(stack))
{
str2=(char*)stackPop(stack);
printf("%s\n",str2);
}
}
return 0;
}
stack.h=================================
#include <stdio.h>
struct stackNodeTag
{
void *dataptr;
struct stackNodeTag *link;
};
struct stackTag
{
int count;
struct stackNodeTag *top;
};
struct stackTag *stackCreate(void)
{
struct stackTag *stack;
stack = malloc(sizeof(struct stackTag));
if (stack != NULL)
{
stack->count = 0;
stack->top = NULL;
}
return stack;
}
int stackPush(struct stackTag *stack,
void *dataptr)
{
struct stackNodeTag *newptr;
newptr = malloc(sizeof(struct stackNodeTag));
if (newptr == NULL) return 0;
newptr->dataptr = dataptr;
newptr->link = stack->top;
stack->top = newptr;
(stack->count)++;
return 1;
}
void *stackPop(struct stackTag *stack)
{
void *dataptr;
if (stack->count == 0)
dataptr = NULL;
else
{
dataptr = stack->top->dataptr;
stack->top = stack->top->link;
(stack->count)--;
}
return dataptr;
}
void *stackGet(struct stackTag *stack)
{
if (stack->count == 0)
return NULL;
else
return stack->top->dataptr;
}
int stackEmpty(struct stackTag *stack)
{
return (stack->count == 0);
}
int stackFull(struct stackTag *stack)
{
struct stackNodeTag *nodeptr;
if ((nodeptr = malloc(sizeof(*(stack->top)))))
{
free(nodeptr);
return 0;
}
return 1;
}
int stackCount(struct stackTag *stack)
{
return stack->count;
}
struct stackTag *stackRelease(struct stackTag *stack)
{
struct stackNodeTag *nodeptr;
if (stack)
{
while (stack->top != NULL)
{
free(stack->top->dataptr);
nodeptr = stack->top;
stack->top = stack->top->link;
free(nodeptr);
}
free(stack);
}
return NULL;
}
補充說明:
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.84.27.29
→
10/18 18:18, , 1F
10/18 18:18, 1F
→
10/18 18:23, , 2F
10/18 18:23, 2F
→
10/18 18:27, , 3F
10/18 18:27, 3F
→
10/18 18:28, , 4F
10/18 18:28, 4F
→
10/18 18:46, , 5F
10/18 18:46, 5F
→
10/18 18:47, , 6F
10/18 18:47, 6F
→
10/18 18:52, , 7F
10/18 18:52, 7F
→
10/18 19:00, , 8F
10/18 19:00, 8F
→
10/18 19:01, , 9F
10/18 19:01, 9F
推
10/18 20:37, , 10F
10/18 20:37, 10F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章