DEV Community

Leo
Leo

Posted on • Updated on

Invertir una cadena

Image description

Image description

Here we have the code in C++ to resolve problem.

main.cpp

/*
AUTOR:    Leobardo Vázquez 
CURSO:    Estructura de Datos
PROGRAMA: Invertir una cadena
FECHA:    22 de Marzo del 2024
*/
#include <iostream>
#include "string.hpp"

int main() {

  stack s(100);
  std::string str;
  getline (std::cin, str);
  for (int i = 0; i < str.length(); i++) s.push(str[i]);
  s.print();
  return 0;
}
//https://dev.to/imnotleo/invertir-una-cadena-o47
Enter fullscreen mode Exit fullscreen mode

string.cpp

#include "string.hpp"

stack::node::node(char x) {
  _data = x;
  _next = nullptr;
}

stack::stack(int m){

  n = m;
  s = 0;

  init = nullptr;
}

stack::~stack(){

  while(init != nullptr) {
    node *p = init;
    init = init->next();
    delete p;
  }

}


void stack::push(char x){

  assert(!full());
  node *p = new node(x);
  p -> next(init);
  init = p;

  s++;
}

void stack::print(){

  node *p = init;
  while(p != nullptr){
    std::cout << p -> data();
    p = p -> next();
  }
}
//https://dev.to/imnotleo/invertir-una-cadena-o47
Enter fullscreen mode Exit fullscreen mode

string.hpp

#ifndef string_hpp
#define string_hpp

#include <iostream>
#include <assert.h>
#include <string>

class stack {

  class node {

  char _data;
  node *_next;

  public:

    node(char);

  char data() const { return _data; } //cual es el dato
  node *next() const { return _next; } // cual es el siguiente apuntador
  void next(node *p) { _next = p; } // cambia el siguiente ap
  };

  int n; // Capacity of stack
  int s; // Size of stack

  node *init; // Inicio de nodo

public:

  stack(int);
  ~stack();

  void push(char);


  int capacity() const { return n; }
  int size() const { return s; }

  bool full() const { return s==n; }
  bool empty() const { return s==0; }

  void print();
};

#endif /* string_hpp */
//https://dev.to/imnotleo/invertir-una-cadena-o47
Enter fullscreen mode Exit fullscreen mode

Top comments (0)