[问题] linklist制作stack

楼主: f422661 (恩恩)   2015-12-14 00:27:10
开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
问题(Question):
stack push 失败
明明用除错看push return top 都是成功把值放到stack里的
结果一return回main function top又是指向null而不是我push进去的node
求各位大大帮忙指点问题了..
喂入的资料(Input):
3 ,5
预期的正确结果(Expected Output):
3,5
错误结果(Wrong Output):

程式码(Code):(请善用置底文网页, 记得排版)
struct node {
int data;
struct node *next;
};
typedef struct node Node;
Node* push(Node* top, int item);
void show(Node* a);
int _tmain(int argc, _TCHAR* argv[])
{
Node *top=NULL;
push(top,3);
push(top,5);
show(top);
return 0;
}
Node* push(Node* top, int item) {
Node* temp;
temp = (Node*) malloc(sizeof(Node));
temp->data = item;
temp->next = top;
top = temp;
return top;
}
void show(Node* top)
{
Node* tmpnode;
tmpnode = top;
printf("\n堆叠内容:");
while(tmpnode != NULL) {
printf("%d ", tmpnode->data);
tmpnode = tmpnode->next;
}
}
补充说明(Supplement):
作者: remizu (remizu)   2015-12-14 00:40:00
return的top没有接住 还有十三戒之13
作者: OPIV (Monitor)   2015-12-14 00:51:00
正确结果是5、3吧
作者: hl4 (Zec)   2015-12-14 01:35:00
push(&top)
作者: tsoahans (ㄎㄎ)   2015-12-14 01:41:00
call by value/reference的问题
作者: OPIV (Monitor)   2015-12-14 03:09:00
是 call by pointer 没错,但是因为你动到 pointer 本身的值了,所以要 pass pointer to pointer 才行
作者: LPH66 (-6.2598534e+18f)   2015-12-14 03:38:00
所以说 cbp 这讲法会让人混淆就是这样你要改动一个变量就传它的位址进去即可, 不论这变量是什么
作者: stupid0319 (征女友)   2015-12-14 07:44:00
不才认为typedef struct node *Node;这样写比较好你的stack的next应该是指向上一个,写next有点怪怪的

Links booklink

Contact Us: admin [ a t ] ucptt.com