我有三个文件:stack2.h、stack2.c 和 main.c。
stack2.h 包含以下内容:
/* Define linked list structure */
typedef struct node {
int val;
struct Node *next;
} Node, *pNode;
/* Define stack structure */
typedef struct StackType {
pNode top;
} Stack, *pStack;
/* Declare functions */
pStack InitStack( );
int IsEmpty( pStack pS );
int Pop( pStack pS );
void Push( pStack pS, int val );
void KillStack( pStack pS );
stack2.c 包含
pStack InitStack( ) {
/* Declare variables */
pStack pS = (pStack)malloc( sizeof(Stack) );
/* Set first node to NULL */
pS -> top = NULL;
/* Return pointer to stack */
return pS;
}
int IsEmpty( pStack pS ) {
return ( pS->top == NULL );
}
int Pop( pStack pS ) {
/* Declare variables */
int ret = 0;
pNode temp = NULL;
/* Check if stack is empty */
if( IsEmpty( pS ) ) {
printf( "[ERROR] Pop operation on an empty stack.\n" );
exit( 1 );
}
/* Find return value (last in) */
ret = pS->top->val;
temp = pS->top;
/* Delete and kill node */
pS->top = pS->top->next;
free( temp );
/* Return */
return ret;
}
void Push( pStack pS, int val ) {
/* Allocate memory for new node */
pNode nnew = (pNode)malloc( sizeof(Node) );
/* Initiate node */
nnew->next = pS->top;
nnew->val = val;
/* Set structure's top to new node */
pS -> top = nnew;
}
我不会用 main.c 包含的内容给你带来负担。本质上,它包括正确的库和文件,并且只是简单地推送和弹出一些值。我收到这些警告:
assignment from incompatible pointer types
在这两行:
nnew->next = pS->top;
pS->top = pS->top->next;
我有点困惑。nnew 是指向节点的指针,因此 nnew->next 也是指向节点的指针。pS 是指向堆栈的指针,因此 pS->top 也是指向节点的指针。我不明白这些是如何不兼容的!
这是怎么回事?谢谢!