#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[110],a[110];
typedef struct node//建立一个链表
{
char data;
struct node *next;
}node,*linklist;
int Ismatch(linklist head)
{
node *ptr1,*ptr2,*ptr3,*ptr4;
ptr1=head->next;
ptr2=ptr1->next;
ptr3=ptr2->next;
ptr4=ptr3->next;
while(ptr2!=NULL&&ptr1!=NULL)
{
if(ptr2->data-ptr1->data==1||ptr2->data-ptr1->data==2)
{
ptr1=ptr3;
ptr2=ptr4;
free(ptr3);
free(ptr4);
ptr1=head->next;
ptr2=ptr1->next;
ptr3=ptr2->next;
ptr4=ptr3->next;
}
else
continue;
}
if(ptr2==NULL&&ptr1==NULL)
return 1;
else
return 0;
}
int main()
{
int i=0,t=0,n=0,m=0;
node *p,*q;
p=NULL; q=NULL;
linklist head;
head=(node *)malloc(sizeof(node));
head->next=NULL;
p=head;
while(scanf("%s",s)!=EOF)
{
int i=0,n=0,m=0;
n=strlen(s);
p=head;
for(i=0;i<n;i++)
{
//只将输入的字符中的括号写入链表
if(s[i]=='('||s[i]==')'||s[i]=='['||s[i]==']'||s[i]=='{'||s[i]=='}')
{
q=(node *)malloc(sizeof(node));
q->data=s[i];
p->next=q;
p=q;
}
else
continue;
}
q->next=NULL;
m=Ismatch(head);
if(m==1)
printf("yes\n");
else
printf("no\n");
}
return 0;
}
我看在您的代码中,您没有为链表的最后一个节点分配空间,因此程序会崩溃。此外,您在while循环中未将变量i重置为0,这可能导致错误的计数器值。以下是我已经修复的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[110],a[110];
typedef struct node
{
char data;
struct node *next;
}node,*linklist;
int Ismatch(linklist head)
{
node *ptr1,*ptr2,*ptr3,*ptr4;
ptr1=head->next;
ptr2=ptr1->next;
ptr3=ptr2->next;
ptr4=ptr3->next;
while(ptr2!=NULL&&ptr1!=NULL)
{
if(ptr2->data-ptr1->data==1||ptr2->data-ptr1->data==2)
{
ptr1=head->next;
ptr2=ptr1->next;
ptr3=ptr2->next;
ptr4=ptr3->next;
free(ptr3);
free(ptr4);
}
else
{
ptr1=ptr2;
ptr2=ptr3;
ptr3=ptr4;
ptr4=ptr4->next;
}
}
if(ptr2==NULL&&ptr1==NULL)
return 1;
else
return 0;
}
int main()
{
int i=0,t=0,n=0,m=0;
node *p,*q;
p=NULL; q=NULL;
linklist head;
head=(node *)malloc(sizeof(node));
head->next=NULL;
p=head;
while(scanf("%s",s)!=EOF)
{
int i=0,n=0,m=0;
n=strlen(s);
p=head;
for(i=0;i<n;i++)
{
if(s[i]=='('||s[i]==')'||s[i]=='['||s[i]==']'||s[i]=='{'||s[i]=='}')
{
q=(node *)malloc(sizeof(node));
q->data=s[i];
p->next=q;
p=q;
}
else
continue;
}
q->next=NULL;
m=Ismatch(head);
if(m==1)
printf("yes\n");
else
printf("no\n");
p=head->next;
while(p!=NULL)
{
q=p->next;
free(p);
p=q;
}
head->next=NULL;
}
return 0;
}
此代码现在应该可以输出正确的结果了。
https://www.bilibili.com/video/BV1PA411b75a?p=92
https://github.com/tangtangcoding/C-C-
https://www.bilibili.com/video/BV1jK4y1m7d4