Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11721

Error in linked list implementation of stack

$
0
0

I want to do linked list implementation of stack however my code is not working as expected.I am not able to discover whats causing the issue hence i will be posting my code, the present output and ideal output.i could not figure how to add in if condition that n is alphabet then execute if statement for input like no. 456 or execute else statement.kindly help if you figure the issue.

CODE:

#include <stdio.h>#include <stdlib.h>struct node{    char data;    struct node *next;};struct node*head;void push(char x){    if (head == NULL) {        head= (struct node*) malloc(sizeof(struct node));        head->data=x;        head->next=NULL;        printf("additon successful\n");                return ;    }    struct node *temp = (struct node*) malloc(sizeof(struct node));    temp->next=head;    temp->data=x;    head=temp;    printf("additon successful\n");      return ;}void pop(){    if(head == NULL){        printf("list is empty\n");        return ;}struct node *temp = (struct node*) malloc(sizeof(struct node));temp=head;head=head->next;free(temp);printf("pop is successful\n");return ;}void print(){    struct node *temp = (struct node*) malloc(sizeof(struct node));    temp=head;    while(temp != NULL){        printf("%c  ",temp->data);        temp=temp->next;    }    printf("\nall items printed\n");    return ;}void main() {    char n;    printf("enter alphabet\n");    while (0!=1){    scanf("%c",&n);    if(n != 1 && n!= '`'&& n!= 4 ) {    push(n);}    else if(n == 1) {    pop();}    else if(n == '`') {    print();}    else if(n == 4) {    printf("\nexiting program");    return ;}    else {    printf("enter valid argument\n");}    }}

OUTPUT:

enter alphabetradditon successful             // why is this printing twice?additon successfulaadditon successfuladditon successfulnadditon successfuladditon successfuldadditon successfuladditon successful1                               // for 1 code should perform pop operationadditon successfuladditon successful4                               // for 4 function should end        additon successfuladditon successful456                             // i could not figure how to add  in if condition that n is                                    aplphabet then execute if statement for such no. like 456                                    execute else additon successfuladditon successfuladditon successful              //why so many executions?additon successful

IDEAL OUTPUT:

1list is emptyradditon successfuleadditon successfulaadditon successfuldadditon successful1pop is successful1pop is successful`a  dall items printed456enter valid argument4exiting program

Viewing all articles
Browse latest Browse all 11721

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>