问题描述
我正在尝试使用链表实现的堆栈来检查给定的括号数组是否平衡。我已经声明了一个全局结构指针。其余的代码是这样的。
struct node *Head;
struct node
{
char data;
struct node *next;
};
struct node *getnewnode(char x)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = x;
temp->next = NULL;
return temp;
}
void push(char x)
{
printf("Pushing:%c\n",x);
struct node *temp = getnewnode(x);
if (Head == NULL)
Head = temp;
struct node *temp2 = Head;
temp->next = temp2;
Head = temp;
}
void pop()
{
struct node *temp = Head;
if (temp == NULL)
printf("nothing to POP");
else
{
printf("POPing : %c\n",Head->data);
Head = temp->next;
free(temp);
}
}
int main()
{
Head = NULL;
char C[] = "{()}";
for (int i = 0; i < strlen(C); i++)
{
if (C[i] == '{' || C[i] == '[' || C[i] == '(')
{
push(C[i]);
printf("Push :%c\n",Head->data);
}
else if (C[i] == '}' || C[i] == ']' || C[i] == ')')
{
if (Head == NULL)
{
printf("nothing in stack\n");
}
else if (C[i] == ']' && Head->data == '[')
pop();
else if (C[i] == '}' && Head->data == '{')
pop();
else if (C[i] == ')' && Head->data == '(')
pop();
//else
// return 0;
}
}
printf("Present Stack:%c\n",Head->data);
if (Head->data == -1)
printf("Balanced");
else if (Head->data != -1)
{
printf("not Balanced");
}
}
我得到的输出是这个
Pushing:{
Push :{
Pushing:(
Push :(
POPing : (
POPing : {
Present Stack:ÿ
not Balanced
如您所见,数组的所有元素都被弹出,但输出仍然不平衡。堆栈中仍然存在我不知道的值 'ÿ'
。
有人可以指出这段代码有什么问题。我是不是遗漏了什么。
解决方法
你的推送应该是
void push(char x)
{
printf("Pushing:%c\n",x);
struct node* temp = getnewnode(x);
temp.next = Head;
Head = temp;
}