[英]Why is the Stack not getting Emptied in this balanced parenthesis check C Program?
I am trying to check whether the given array of parenthesis are balanced or not using linked list implemented stack.I have declared a global struct pointer.我正在尝试使用链表实现的堆栈检查给定的括号数组是否平衡。我已经声明了一个全局结构指针。 And the rest of the code is this.
而代码的rest就是这个。
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");
}
}
The output that I am getting is this我得到的output就是这个
Pushing:{
Push :{
Pushing:(
Push :(
POPing : (
POPing : {
Present Stack:ÿ
not Balanced
As you can see that the all the elements of the array are getting popped, still the output is not balanced.如您所见,数组的所有元素都被弹出,output 仍然不平衡。 There is still the value
'ÿ'
in the stack which I have no idea of.堆栈中仍然存在我不知道的值
'ÿ'
。 Could someone kindly point out what's wrong in this code.有人可以指出这段代码有什么问题。 Am I missing something.
我是不是错过了什么。
Your push should just be你的推动应该只是
void push(char x)
{
printf("Pushing:%c\n", x);
struct node* temp = getnewnode(x);
temp.next = Head;
Head = temp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.