Skip to content

Instantly share code, notes, and snippets.

@rajivseelam
Created September 19, 2012 03:25
Show Gist options
  • Save rajivseelam/3747492 to your computer and use it in GitHub Desktop.
Save rajivseelam/3747492 to your computer and use it in GitHub Desktop.
Reverse a stack (inplace)
/***
This program is similar to reversing a linked list. I have done anyway for the heck of it!
****/
#include<stdio.h>
#include<stdlib.h>
typedef struct _node {
int value;
struct _node * next;
} node;
typedef node stack;
void printS(stack * L){
node * temp = L;
printf("Stack : ");
while(temp != NULL){
printf("%d ", temp->value);
temp = temp->next;
}
printf("\n");
}
stack * Push(int X, stack * S){
node * temp;
temp = malloc(sizeof(node));
temp->value = X;
if(S==NULL){
return temp;
}
else{
temp->next = S;
return temp;
}
}
int Pop(stack **S){
int i;
i = (*S)->value;
*S = (*S)->next;
return i;
}
stack * RevStack(stack *S){
node *previous, *present, *next;
previous = NULL;
present = S;
next = S->next;
while(present!=NULL){
present->next = previous;
previous = present;
present = next;
if(next!=NULL)
next = next->next;
}
printf("Reversed...\n");
printS(previous);
return previous;
}
int main(){
stack * S = NULL;
int i,X;
while(1){
printf("What do you want to do? 1. Push, 2. Pop 3. Exit 4. Print 5.Reverse\n");
scanf("%d", &i);
switch(i){
case 1:
printf("Enter number:\n");
scanf("%d",&X);
S = Push(X,S);
break;
case 2:
X = Pop(&S);
printf("Popped %d\n",X);
break;
case 4:
printS(S);
break;
case 5:
RevStack(S);
break;
case 3:
exit(1);
default :
printf("Wrong choice\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment