我在C中尝试简单的堆栈实现。这是我的简单代码:
1 #include "stdio.h"
2 #include "limits.h"
3 #include "malloc.h"
4
5 typedef struct StackEntry StackEntry;
6
7 struct StackEntry
8 {
9 int data;
10 StackEntry *next;
11 };
12
13 StackEntry* createStack(){
14 return NULL;
15 }
16
17 int isEmptyStack(StackEntry **pStackTop)
18 {
19 return *pStackTop == NULL;
20 }
21
22 void push(StackEntry **pStackTop, int pData)
23 {
24 StackEntry *lTempStackEntry;
25 lTempStackEntry = (StackEntry*)malloc(sizeof(StackEntry));
26
27 if(!lTempStackEntry)
28 return;
29
30 lTempStackEntry->data = pData;
31 lTempStackEntry->next = *pStackTop;
32
33 *pStackTop = lTempStackEntry;
34 }
35
36 int pop(StackEntry **pStackTop)
37 {
38 int lTempData;
39 StackEntry *lTempStackEntry;
40
41 if(isEmptyStack(pStackTop))
42 return INT_MIN;
43
44 lTempStackEntry = *pStackTop;
45 *pStackTop = (*pStackTop)->next;
46 lTempData = lTempStackEntry->data;
47 free(lTempStackEntry);
48
49 return lTempData;
50 }
51
52 int stackTop(StackEntry **pStackTop)
53 {
54 if(isEmptyStack(pStackTop))
55 return INT_MIN;
56
57 return (*pStackTop)->data;
58 }
59
60 void deleteStack(StackEntry ** pStackTop)
61 {
62 StackEntry *secondTopNode, *topNode;
63 topNode = *pStackTop;
64 /*
65 * In this we free all the nodes from second top to bottom,
66 * by one by one attaching them to top->next. At the end
67 * we free the top node.
68 */
69 while(topNode->next)
70 {
71 secondTopNode = topNode->next;
72 topNode->next = secondTopNode->next; //make third top node
73 //second top node
74 free(secondTopNode);
75 secondTopNode = NULL;
76 }
77 free(topNode);
78 topNode = NULL;
79 }
80
81 int main(void) {
82 // your code goes here
83 StackEntry *stack = createStack(); //stack: 0x0
84 printf("\n push 1");
85 push(&stack,1);
86 printf("\n push 2");
87 push(&stack,2);
88 printf("\n push 3");
89 push(&stack,3);
90 printf("\n stack top: %d", stackTop(&stack));
91 printf("\n pop: %d ",pop(&stack));
92 printf("\n stack top: %d", stackTop(&stack));
93 printf("\n pop: %d ",pop(&stack));
94 printf("\n stack top: %d", stackTop(&stack));
95
96 deleteStack(&stack);
97 printf("\n stack deleted.");
98 printf("\n is stack empty: %d", isEmptyStack(&stack)); //here it should print 1, but its printing 0
99
100 printf("\n push 1");
101 push(&stack,1);
102 printf("\n push 2");
103 push(&stack,2);
104
105 printf("\n pop: %d ",pop(&stack));
106 printf("\n pop: %d ",pop(&stack));
107 return 0;
108 }
输出
push 1
push 2
push 3
stack top: 3
pop: 3
stack top: 2
pop: 2
stack top: 1
stack deleted.
is stack empty: 0
push 1
push 2
pop: 2
pop: 1
在deleteStack()
中,我释放所有堆栈条目并将堆栈顶部设置为NULL
。在isEmptyStack()
中检查堆栈顶部是否为空。所以它应该评估为1
并且第98行应该打印1(即为真),但是它打印为0。
这里有什么不对? Here is the code on ideone
我采取的调试工作:
答案 0 :(得分:2)
在函数deleteStack
中,不要将stack设置为null,而是将堆栈指针的副本设置为null。
你做的是:
topNode = *pStackTop;
topNode = NULL;
哪个不对。
你应该做的是:
*pStackTop = NULL;