Skip to content

Instantly share code, notes, and snippets.

@oca159
Forked from codepainkiller/invertir_cadena.cpp
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oca159/bd0c52df4f18f5656324 to your computer and use it in GitHub Desktop.
Save oca159/bd0c52df4f18f5656324 to your computer and use it in GitHub Desktop.
/*
* C++ - Invertir cadena / Pilas(stack)
* Copyright 2014 Martin Cruz Otiniano
* Description: Invierte los caracteres de una cadena usando una pila
* Site: www.marcsdev.com
*/
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
struct nodo{
char dato;
struct nodo *sgte;
};
typedef struct nodo *TPila;
/* Crear Nodo
------------------------------------------------------------------*/
TPila crearNodo(char x)
{
TPila newNodo = new(struct nodo);
newNodo->dato = x;
return newNodo;
}
/* Apilar
------------------------------------------------------------------*/
void push(TPila &top, char x)
{
TPila aux = crearNodo(x);
aux->sgte = top;
top = aux;
}
/* Desapilar
------------------------------------------------------------------*/
char pop(TPila &top)
{
int c ;
TPila aux;
aux = top ;
c = aux->dato; // asignamos el primer vamor de la pila
top = aux->sgte ;
delete(aux);
return c;
}
/* Invertir cadena
------------------------------------------------------------------*/
void invertirCadena( TPila &p, string &cad )
{
/* Copiando caracteres a la pila */
for(int i=0; i<cad.size(); i++)
push(p, cad[i]);
/* Desapilando y remplanzando en la cadena */
for(int i=0; i<cad.size(); i++)
cad[i] = pop( p );
}
/* FUNCION PRNCIPAL
------------------------------------------------------------------*/
int main()
{
TPila pila = NULL; // creando Pila
string cad;
cout<<"\n\t\tINVERTIR CADENA USANDO PILA (STACK) \n\n";
cout << " Ingrese palabra: ";
getline(cin, cad);
invertirCadena( pila, cad );
cout << "\n\n Cadena invertida: " << cad <<endl;
cout<<"\n\n ";
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment