判断回文

栈实现回文判断

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

转载于:https://my.oschina.net/yejq08/blog/415581

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值