第八章十一题powerby spritsq

来源:互联网 发布:中国历年进出口数据 编辑:程序博客网 时间:2024/06/05 08:55

//
//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;
 }
}

原创粉丝点击