码迷,mamicode.com
首页 > 其他好文 > 详细

判断回文

时间:2015-05-16 01:43:38      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

Decription:

输入一个字符串,判断其是否为回文。

是则输出,“True”,否则输出“False”

题目最简单的做法就是,用两个指针指向字符串的首尾,然后逐个比对。


下面使用栈来判断:

        将字符串全部push到栈里面,然后逐一pop出来跟原字符串中的字符逐一比较就能得到结果

#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct node {
  int data;
  struct node * next;
} node;

node * push(node * head, int a) {
  node * toPush = (node *)malloc(sizeof(node));
  toPush->data = a;
  toPush->next = NULL;
  
  if(head == NULL) {
    return toPush;
  }

  node * Positoner = head;
  while(Positoner->next != NULL) {
    Positoner = Positoner->next;
  }

  Positoner->next = toPush;
  return head;
}

node * pop(node * head, int * del) {
  if(head == NULL) {
    return NULL;
  }
  
  node * Positoner = head;
  node * saver = NULL;
  while(Positoner->next != NULL) {
    saver = Positoner;
    Positoner = Positoner->next;
  }

  if(saver != NULL)
    saver->next = NULL;
  
  *del = Positoner->data;

  if(Positoner == head) {
    head = NULL;
  }
  
  free(Positoner);
  return head;
}

int main() {
  node * head = NULL;
  int data[1000];
  int del;
  int n;
  int i;

  scanf("%d", &n);

  for(i = 0; i < n; i++) {
    scanf("%d", data+i);
  }
  
  for(i = 0; i < n; i++) {
    head = push(head, data[i]);
  }

  for(i = 0; i < n; i++) {
    head = pop(head, &del);
    if(del != data[i]) {
      printf("False\n");
      return 0;
    }
  }
  printf("True\n");
  return 0;
}


举一反三,给定一个栈,判断是否是回文

我们只需要再新建一个栈,然后将一半(n/2)的元素压入新栈就好,然后判断两个栈的栈顶元素是否相等,若不等,则返回False

IsPalindromeStack(node * stack, int n) {
  if(stack == NULL || stack->next == NULL) {
    return 1;
  }
  node * new_stack = NULL;
  int i;
  int del;
  int del2;
  
  for(i = 0; i < n/2; i++) {
    stack = pop(stack, &del);
    new_stack = push(new_stack, del);
  }

  while(new_stack != NULL) {
    stack = pop(stack, &del);
    new_stack = pop(new_stack, &del2);
    if(del != del2)
      return 0;
  }
  return 1;
}


出处:The-Art-Of-Programming-By-July

https://github.com/julycoding/The-Art-Of-Programming-By-July

判断回文

标签:

原文地址:http://my.oschina.net/yejq08/blog/415581

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!