Logo 
Search:

C Programming Forum

Ask Question   UnAnswered
Home » Forum » C Programming       RSS Feeds

C: Check if string is a palindrome using stack as singly linked list

  Asked By: Nemanja    Date: Nov 07    Category: C Programming    Views: 1082
  

The following program should check if string is a palindrome,
using stack as singly linked list with defining struct STRING
which represents a string without blank spaces:

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

typedef struct
{
char str[100];
}STRING;

typedef struct node
{
STRING info;
struct node *next;
}NODE;

//add node to stack
void push(NODE **tos,STRING *info)
{
NODE *new_node=(NODE *)malloc(sizeof(NODE));
new_node->info=*info;
new_node->next=*tos;
*tos=new_node;
}

//remove node from stack
int pop(NODE **tos,STRING *info)
{
if(*tos == 0)
return 0;
NODE *p=*tos;
*info=p->info;
*tos=p->next;
free(p);
return 1;
}

//check if palindrome
int palindrome(STRING *info)
{
int i;
int len=strlen(info->str);
int cnt=0;
NODE **tos;

//add until length
for(i=0;i<len;i++)
push(&tos,&info->str[i]);

//count while pop() is true
for(i=0;i<len;i++)
{
if(pop(tos,&info->str[i]))
cnt++;
}

//if count is equal length
if(cnt == len)
return 1;
else return 0;
}

int main()
{
NODE *tos=0;
STRING info;
printf(" enter a string: ");
scanf("%s",info.str);
int check=palindrome(&info);
if(check == 1)
printf(" string is a palindrome. ");
else printf(" string is not a palindrome. ");
return 0;
}

Segmentation faults:

(compiler: GNU GCC Compiler)
47|warning: passing argument 1 of 'push' from incompatible pointer type [enabled by default]|
17|note: expected 'struct NODE **' but argument is of type 'struct NODE ***'|
47|warning: passing argument 2 of 'push' from incompatible pointer type [enabled by default]|
17|note: expected 'struct STRING *' but argument is of type 'char *'|
52|warning: passing argument 2 of 'pop' from incompatible pointer type [enabled by default]|
26|note: expected 'struct STRING *' but argument is of type 'char *'|

Share: 

 

No Answers Found. Be the First, To Post Answer.

 




Tagged: