-
-
Save oca159/bd0c52df4f18f5656324 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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