数据结构-堆栈

#include
#include
/node/
typedef struct Node {
int data;
struct Node* pNext;
}NODE,*PNODE;

typedef struct Stack {
PNODE pTop;//栈顶
PNODE pBottom;//栈底部
}STACK,*PSTACK;

PNODE initStack(PSTACK pS)
{
PNODE pHead;
pHead = (PNODE)malloc(sizeof(NODE));
if(pHead == NULL)
printf(“malloc pS fail\n”);
pS->pTop = pHead;
pS->pBottom = pHead;
pS->pBottom->pNext = NULL;
return pHead;
}

void pushStack(PSTACK pS, int val)
{
PNODE pNew;
pNew = (PNODE)malloc(sizeof(NODE));
if(pNew == NULL)
printf(“malloc pNew fail\n”);
pNew->data = val;
//pS->pTop->pNext = pNew;//这个是关键 起到链接的作用 这个不行 针往上指了不便于遍历
pNew->pNext = pS->pTop;
pS->pTop = pNew;
}
void traverse(PSTACK pS)
{
PNODE pMov = pS->pTop;
/* while(pS->pTop->pNext != NULL){不能移动pTop的指向 它永远指向栈顶
pS->pTop = pS->pTop->pNext;
printf("%d",pS->pTop->data);
} */
while(pMov != pS->pBottom) {
printf("%d",pMov->data);
pMov = pMov->pNext;
}
printf("\n");
}
int pop_stack(PSTACK pS)
{
free(pS->pTop);
pS->pTop = pS->pTop->pNext;
}

int main(void)
{
STACK S;
initStack(&S);
pushStack(&S,4);
//pushStack(&S,2);
printf(“pTop->data = %d\n”,S.pTop->data);
pushStack(&S,2);
printf(“pTop->data = %d\n”,S.pTop->data);
traverse(&S);
pop_stack(&S);
traverse(&S);
return 0;
}
/*为什么pop_stack和pushStack的pS是同一个吗
答:是同一个因为传递的地址是一样的,也就是操作的内存区域是一样,相当于指针的copy
&S也是一个指针
initStack(&S); --------->PNODE initStack(PSTACK pS)
pushStack(&S,4);-------->void pushStack(PSTACK pS, int val)
操作的都是一个内存这个内存保存在堆区 这个两个pS可以理解为是同一个pS;函数执行完之后这个指针变量被释放掉了但是他指向的内存还在。
&S *pS 数组名 函数名都是指针
*/

你可能感兴趣的:(C语言,数据结构)