Sunday, 10 August 2014

Palindrome using a stack and a que using linked list in C program.

Palindrome using a stack and a que using linked list

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int val;
    struct node *next;
}*top1,*last,*first;

void push(struct node **top,int val)
{
    struct node *n1 =(struct node *)malloc(sizeof(struct node));   
    n1->val= val;
    n1->next = NULL;   
    if(*top == NULL)
    {
        *top = n1;
       
    }
    else
    {
        n1->next = *top;
        *top = n1;
    }   
}
int pop(struct node **top)
{
    int a;   
    struct node *save = *top;   
    *top = (*top)->next;   
    a = save->val;   
    free(save);
    return a;
       
}

void insert(struct node **last,struct node **first, int val)
{
    struct node *n1 =(struct node*)malloc(sizeof(struct node));
    n1->val = val;
    n1->next = NULL;
    if(*last == NULL)
    {
        *last = n1;
        *first = n1;
    }
    else
    {       
        (*last)->next=n1;
        *last = (*last)->next;
    }   
}
int delete(struct node **first)
{
    int a;   
    struct node *save = *first;   
    *first = (*first)->next;   
    a = save->val;   
    free(save);
    return a;
}

void main()
{
    int num;
    int flag = 0;
    int digit,val,val1,val2;
    printf("Enter number");
    scanf("%d",&num);
    while(num != 0)
    {
        digit = num%10;
        num =num/10;
        push(&top1,digit);
        insert(&last,&first,digit);
    }
    while(top1 != NULL)
    {
        val1= pop(&top1);
        printf("val 1 is %d\n",val1);       
        val2= delete(&first);
        printf("val 2 is %d\n",val2);
             if(val1!=val2)
        flag = 1;               
    }   
    if(flag==1)
    printf("not palidrom\n");   
    else
    printf("palidrom\n");   
       
}

No comments:

Post a Comment