求助!(利用栈)判断单链表中n个字符是否对称,运行时为啥产生了访问违例》.《
#include<stdio.h>#include<stdlib.h>
#include<string.h>
typedef struct node
{
char ch;
struct node*next;
}linklist;
struct Stack
{
char elements[100];
int Top;
};
linklist*head,*p,*q,*r;
Stack*S;
int n;
linklist*CREATLISTR();
void DELETE(linklist*p,linklist*head);
struct Stack*PUSHS(struct Stack*S,char E);
char POPS(struct Stack*S);
int main(void)
{
int i,k;
char ch2;
S = NULL;
printf("Enter n:\n");
scanf("%d",&n);
printf("Enter %d characters:\n",n);
if(n>0)
{
head = CREATLISTR();
p = head->next;
for(k=1;k<=n/2;k++)
{
S = PUSHS(S,p->ch);
r = p;
p = p->next;
DELETE(r,head);
}
if(n%2!=0)
{
q = head->next;
DELETE(q,head);
}
q = head->next;
k = 0;
for(i=1;i<=n/2;i++)
{
ch2 = POPS(S);
if(q->ch!=ch2)
{
printf("字符不对称!\n");
k++;
break;
}
p = p->next;
}
if(k==0)
printf("字符对称!\n");
}
else printf("Error!\n");
}
linklist*CREATLISTR()
{
char ch3;
int t=0;
linklist*head ,*s,*r;
head=(linklist*)malloc(sizeof(linklist)); /*生成头结点head*/
r=head; /*尾指针指向头结点*/
for(t=0;t<n;t++)
{
ch3=getchar();
s=(linklist*)malloc(sizeof(linklist)); /*给新结点分配空间*/
s->ch=ch3; r->next=s; /*新结点插入表尾*/
r=s; /*尾指针r指向新的表尾*/
}
r->next=NULL;
return head; /*返回表头指针*/
}
void DELETE(linklist*p,linklist*head)
{
linklist*q;
q=head;
while(q->next!=p)
q=q->next; /*查找*p的前趋结点*q*/
q->next=p->next; /*删除结点*p*/
free(p);
}
struct Stack*PUSHS(struct Stack*S,char E)
{
S->Top++;
S->elements[S->Top]=E;
return(S);
}
char POPS(struct Stack*S)
{
char temp;
S->Top--;
temp=S->elements[S->Top+1];
return(temp);
}