关闭

第八章十一题powerby spritsq

458人阅读 评论(0) 收藏 举报

//
//8_11 判断字符串是否是对称的
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define MAXSIZE 1024

typedef char datatype;

struct stack
{
 datatype elements[MAXSIZE];
 int top;
};

struct node
{
 char data;
 struct node *next;
};
typedef node linklist;

//创建字符串
linklist *Creat()
{
 linklist *head,*node,*r;
 head = NULL;
 r = NULL;
 char ch;
 printf("请输入一个字符串(以$结束):/n");
 ch = getche();
 printf("/n");
 while(ch != '$')
 {
  node = (linklist *)malloc(sizeof(linklist));
  node->data = ch;
  if(head == NULL)head = node;
  else r->next = node;
  r = node;
  printf("请输入一个字符:/n");
  ch = getche();
  //ch = getchar();
  printf("/n");
 }
 if(r != NULL)
  r->next = NULL;
 return head;
}
//测量字符串长度
int ListLen(linklist *p)
{
 linklist *temp = p;
 int length = 0;
 if(temp == NULL)
 {
  printf("字符串为空!");
 }
 else
 {
  while(temp)
  {
   length++;
   temp = temp->next;
  }
 }
 return (length);
}
void SetNull(struct stack *s)
{
 s->top = -1;
}
int Empty(struct stack *s)
{
 if(s->top >= 0) return (0);
 else return (1);
}
//进栈:将字符串的一半压入栈内
struct stack *Push(struct stack *s,linklist *p)
{
 int len = ListLen(p);
 if(s->top >= MAXSIZE-1)
 {
  printf("stack overflow!");
  return NULL;
 }
 else
 {
  for(int i=0; i<(len/2); i++)
  {
   s->top++;
   s->elements[s->top] = p->data;
   p = p->next;
  }
 }
 return (s);
}

//出栈
datatype Pop(struct stack *s)
{
 datatype temp;
 if(Empty(s))
 {
  printf("Stack underflow!");
  return (-1);
 }
 else
 {
  s->top--;
  temp = s->elements[s->top+1];
  return (temp);
 }
}
//比较字符串
int Compare(struct stack *s,linklist *p)
{
 datatype temp;
 int len, mid,count;
 len = ListLen(p);
 if(len%2 == 0)
 {
  mid = len/2;
 }
 else mid = len/2 +1;

 for(int i=0; i<mid; i++)
 {
  p = p->next;
 }

 count = 0;
 while((!Empty(s))&&p)
 {
  temp = Pop(s);
  if(temp != p->data)
  {
   printf("该字符串不是对称字符串!");
   return (0);
  }
  else
   p = p->next;
   count++;
 }
 if(((len%2 == 0)&&(count == mid))||((len%2 != 0)&&(count == mid-1)))
  return (1);
}

void main()
{
 linklist *strlist;
 stack *str;
 str = (stack *)malloc(sizeof(stack));
 strlist = Creat();
 SetNull(str);

 Push(str,strlist);
 if(Compare(str,strlist))
 {
  while(strlist)
  {
   printf("%c",strlist->data);
   strlist = strlist->next;
  }
  printf("/n该字符串是一对称字符串!");
 }
 //释放资源……
 while(strlist)
 {
  free(strlist);
  strlist = strlist->next;
 }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:34025次
    • 积分:746
    • 等级:
    • 排名:千里之外
    • 原创:40篇
    • 转载:0篇
    • 译文:0篇
    • 评论:3条