Reverse a string using stack

Given a string which contains alphabet characters, Our goal is to reverse the string using stack. For example.

Input  : Character
OutPut : retcarahC

In this post includes two mechanisms to solve this problem. Using custom stack functionality based on linked list. And another way, by using of predefined stack. Custom class implementation of Stack.

// Java program
// Reversing string using stack

// Stack node
class StackNode
{
    // Stack data
    public char element;
    public StackNode next;
    public StackNode(char element, StackNode next)
    {
        this.element = element;
        this.next = next;
    }
}
// Define a custom stack
class MyStack
{
    public StackNode top;
    public int size;
    public MyStack()
    {
        // Set node values
        this.top = null;
        this.size = 0;
    }
    // Add node at the top of stack
    public void push(char element)
    {
        this.top = new StackNode(element, this.top);
        this.size++;
    }
    public boolean isEmpty()
    {
        if (this.size > 0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    public void pop()
    {
        if (this.size > 0 && this.top != null)
        {
            StackNode temp = this.top;
            // Change top element of stack
            this.top = temp.next;
            this.size--;
        }
    }
    // Return top element of stack
    public char peek()
    {
        return this.top.element;
    }
}
public class ReverseString
{
    // Reverse the string element
    public String reverse(String text)
    {
        int size = text.length();
        // Auxiliary variable which is used to store result of string
        String result = "";
        // Create an stack
        MyStack stack = new MyStack();
        // Add element into stack
        for (int i = 0; i < size; i++)
        {
            // Add element into stack
            stack.push(text.charAt(i));
        }
        // iterating the stack elements until if not empty
        while (stack.isEmpty() == false)
        {
            // Get top element
            result += stack.peek();
            // Remove current top
            stack.pop();
        }
        return result;
    }
    public static void main(String[] args)
    {
        ReverseString task = new ReverseString();
        String text = "This is a simple words";
        System.out.print(" Before Reverse : [" + text + "]");
        text = task.reverse(text);
        System.out.print("\n After Reverse : [" + text + "]");
        text = " ABC";
        System.out.print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        System.out.print("\n After Reverse : [" + text + "]");
        text = "BIG WIN";
        System.out.print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        System.out.print("\n After Reverse : [" + text + "]");
        text = "BIG DOG";
        System.out.print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        System.out.print("\n After Reverse : [" + text + "]");
    }
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]

In above approach is based on custom stack implementation. Here first all the elements are inserted into the stack and pop() method is used to collect the resultant text.

Inserting text characters into stack
// Include header file
#include <iostream>
#include <string>
using namespace std;
// C++ program
// Reversing string using stack

// Stack node
class StackNode
{
    public:
    // Stack data
    char element;
    StackNode *next;
    StackNode(char element, StackNode *next)
    {
        this->element = element;
        this->next = next;
    }
};
// Define a custom stack
class MyStack
{
    public: StackNode *top;
    int size;
    MyStack()
    {
        this->top = NULL;
        this->size = 0;
    }
    // Add node at the top of stack
    void push(char element)
    {
        this->top = new StackNode(element, this->top);
        this->size++;
    }
    bool isEmpty()
    {
        if (this->size > 0 && this->top != NULL)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    void pop()
    {
        if (this->size > 0 && this->top != NULL)
        {
            StackNode *temp = this->top;
            // Change top element of stack
            this->top = temp->next;
            this->size--;
        }
    }
    // Return top element of stack
    char peek()
    {
        return this->top->element;
    }
};
class ReverseString
{
    public:
        // Reverse the string element
        string reverse(string text)
        {
            int size = text.length();
            // Auxiliary variable which is used to store result of string
            string result = "";
            // Create an stack
            MyStack *stack = new MyStack();
            // Add element into stack
            for (int i = 0; i < size; i++)
            {
                // Add element into stack
                stack->push(text[i]);
            }
            // iterating the stack elements until if not empty
            while (stack->isEmpty() == false)
            {
                // Get top element
                result += stack->peek();
                // Remove current top
                stack->pop();
            }
            return result;
        }
};
int main()
{
    ReverseString *task = new ReverseString();
    string text = "This is a simple words";
    cout << " Before Reverse : [" << text << "]";
    text = task->reverse(text);
    cout << "\n After Reverse : [" << text << "]";
    text = " ABC";
    cout << "\n Before Reverse : [" << text << "]";
    text = task->reverse(text);
    cout << "\n After Reverse : [" << text << "]";
    text = "BIG WIN";
    cout << "\n Before Reverse : [" << text << "]";
    text = task->reverse(text);
    cout << "\n After Reverse : [" << text << "]";
    text = "BIG DOG";
    cout << "\n Before Reverse : [" << text << "]";
    text = task->reverse(text);
    cout << "\n After Reverse : [" << text << "]";
    return 0;
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
// Include namespace system
using System;
// Csharp program
// Reversing string using stack

// Stack node
public class StackNode
{
    // Stack data
    public char element;
    public StackNode next;
    public StackNode(char element, StackNode next)
    {
        this.element = element;
        this.next = next;
    }
}
// Define a custom stack
public class MyStack
{
    public StackNode top;
    public int size;
    public MyStack()
    {
        // Set node values
        this.top = null;
        this.size = 0;
    }
    // Add node at the top of stack
    public void push(char element)
    {
        this.top = new StackNode(element, this.top);
        this.size++;
    }
    public Boolean isEmpty()
    {
        if (this.size > 0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    public void pop()
    {
        if (this.size > 0 && this.top != null)
        {
            StackNode temp = this.top;
            // Change top element of stack
            this.top = temp.next;
            this.size--;
        }
    }
    // Return top element of stack
    public char peek()
    {
        return this.top.element;
    }
}
public class ReverseString
{
    // Reverse the string element
    public String reverse(String text)
    {
        int size = text.Length;
        // Auxiliary variable which is used to store result of string
        String result = "";
        // Create an stack
        MyStack stack = new MyStack();
        // Add element into stack
        for (int i = 0; i < size; i++)
        {
            // Add element into stack
            stack.push(text[i]);
        }
        // iterating the stack elements until if not empty
        while (stack.isEmpty() == false)
        {
            // Get top element
            result += stack.peek();
            // Remove current top
            stack.pop();
        }
        return result;
    }
    public static void Main(String[] args)
    {
        ReverseString task = new ReverseString();
        String text = "This is a simple words";
        Console.Write(" Before Reverse : [" + text + "]");
        text = task.reverse(text);
        Console.Write("\n After Reverse : [" + text + "]");
        text = " ABC";
        Console.Write("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        Console.Write("\n After Reverse : [" + text + "]");
        text = "BIG WIN";
        Console.Write("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        Console.Write("\n After Reverse : [" + text + "]");
        text = "BIG DOG";
        Console.Write("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        Console.Write("\n After Reverse : [" + text + "]");
    }
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
<?php
// Php program
// Reversing string using stack

// Stack node
class StackNode
{
    // Stack data
    public $element;
    public $next;
    public  function __construct($element, $next)
    {
        $this->element = $element;
        $this->next = $next;
    }
}
// Define a custom stack
class MyStack
{
    public $top;
    public $size;
    public  function __construct()
    {
        $this->top = NULL;
        $this->size = 0;
    }
    // Add node at the top of stack
    public  function push($element)
    {
        $this->top = new StackNode($element, $this->top);
        $this->size++;
    }
    public  function isEmpty()
    {
        if ($this->size > 0 && $this->top != NULL)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    public  function pop()
    {
        if ($this->size > 0 && $this->top != NULL)
        {
            $temp = $this->top;
            // Change top element of stack
            $this->top = $temp->next;
            $this->size--;
        }
    }
    // Return top element of stack
    public  function peek()
    {
        return $this->top->element;
    }
}
class ReverseString
{
    // Reverse the string element
    public  function reverse($text)
    {
        $size = strlen($text);
        // Auxiliary variable which is used to store result of string
        $result = "";
        // Create an stack
        $stack = new MyStack();
        // Add element into stack
        for ($i = 0; $i < $size; $i++)
        {
            // Add element into stack
            $stack->push($text[$i]);
        }
        // iterating the stack elements until if not empty
        while ($stack->isEmpty() == false)
        {
            // Get top element
            $result .= $stack->peek();
            // Remove current top
            $stack->pop();
        }
        return $result;
    }
}

function main()
{
    $task = new ReverseString();
    $text = "This is a simple words";
    echo(" Before Reverse : [".$text.
        "]");
    $text = $task->reverse($text);
    echo("\n After Reverse : [".$text.
        "]");
    $text = " ABC";
    echo("\n Before Reverse : [".$text.
        "]");
    $text = $task->reverse($text);
    echo("\n After Reverse : [".$text.
        "]");
    $text = "BIG WIN";
    echo("\n Before Reverse : [".$text.
        "]");
    $text = $task->reverse($text);
    echo("\n After Reverse : [".$text.
        "]");
    $text = "BIG DOG";
    echo("\n Before Reverse : [".$text.
        "]");
    $text = $task->reverse($text);
    echo("\n After Reverse : [".$text.
        "]");
}
main();

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
// Node JS program
// Reversing string using stack

// Stack node
class StackNode
{
    constructor(element, next)
    {
        this.element = element;
        this.next = next;
    }
}
// Define a custom stack
class MyStack
{
    constructor()
    {
        this.top = null;
        this.size = 0;
    }
    // Add node at the top of stack
    push(element)
    {
        this.top = new StackNode(element, this.top);
        this.size++;
    }
    isEmpty()
    {
        if (this.size > 0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    pop()
    {
        if (this.size > 0 && this.top != null)
        {
            var temp = this.top;
            // Change top element of stack
            this.top = temp.next;
            this.size--;
        }
    }
    // Return top element of stack
    peek()
    {
        return this.top.element;
    }
}
class ReverseString
{
    // Reverse the string element
    reverse(text)
    {
        var size = text.length;
        // Auxiliary variable which is used to store result of string
        var result = "";
        // Create an stack
        var stack = new MyStack();
        // Add element into stack
        for (var i = 0; i < size; i++)
        {
            // Add element into stack
            stack.push(text.charAt(i));
        }
        // iterating the stack elements until if not empty
        while (stack.isEmpty() == false)
        {
            // Get top element
            result += stack.peek();
            // Remove current top
            stack.pop();
        }
        return result;
    }
}

function main()
{
    var task = new ReverseString();
    var text = "This is a simple words";
    process.stdout.write(" Before Reverse : [" + text + "]");
    text = task.reverse(text);
    process.stdout.write("\n After Reverse : [" + text + "]");
    text = " ABC";
    process.stdout.write("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    process.stdout.write("\n After Reverse : [" + text + "]");
    text = "BIG WIN";
    process.stdout.write("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    process.stdout.write("\n After Reverse : [" + text + "]");
    text = "BIG DOG";
    process.stdout.write("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    process.stdout.write("\n After Reverse : [" + text + "]");
}
main();

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
package main
import "fmt"
// Go program
// Reversing string using stack

// Stack node
type StackNode struct {
    // Stack data
    element byte
    next * StackNode
}
func getStackNode(element byte, next * StackNode) * StackNode {
    var me *StackNode = &StackNode {element,next}
    return me
}
// Define a custom stack
type MyStack struct {
    top * StackNode
    size int
}
func getMyStack() * MyStack {
    var me *MyStack = &MyStack {nil,0}
    return me
}
// Add node at the top of stack
func(this *MyStack) push(element byte) {
    this.top = getStackNode(element, this.top)
    this.size++
}
func(this MyStack) isEmpty() bool {
    if this.size > 0 && this.top != nil {
        return false
    } else {
        return true
    }
}
// Remove top element of stack
func(this *MyStack) pop() {
    if this.size > 0 && this.top != nil {
        var temp * StackNode = this.top
        // Change top element of stack
        this.top = temp.next
        this.size--
    }
}
// Return top element of stack
func(this MyStack) peek() byte {
    return this.top.element
}
type ReverseString struct {}
func getReverseString() * ReverseString {
    var me *ReverseString = &ReverseString {}
    return me
}
// Reverse the string element
func(this ReverseString) reverse(text string) string {
    var size int = len(text)
    // Auxiliary variable which is used to store result of string
    var result string = ""
    // Create an stack
    var stack * MyStack = getMyStack()
    // Add element into stack
    for i := 0 ; i < size ; i++ {
        // Add element into stack
        stack.push(text[i])
    }
    // iterating the stack elements until if not empty
    for (stack.isEmpty() == false) {
        // Get top element
        result += string(stack.peek())
        // Remove current top
        stack.pop()
    }
    return result
}
func main() {
    var task * ReverseString = getReverseString()
    var text string = "This is a simple words"
    fmt.Print(" Before Reverse : [", text, "]")
    text = task.reverse(text)
    fmt.Print("\n After Reverse : [", text, "]")
    text = " ABC"
    fmt.Print("\n Before Reverse : [", text, "]")
    text = task.reverse(text)
    fmt.Print("\n After Reverse : [", text, "]")
    text = "BIG WIN"
    fmt.Print("\n Before Reverse : [", text, "]")
    text = task.reverse(text)
    fmt.Print("\n After Reverse : [", text, "]")
    text = "BIG DOG"
    fmt.Print("\n Before Reverse : [", text, "]")
    text = task.reverse(text)
    fmt.Print("\n After Reverse : [", text, "]")
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
#  Python 3 program
#  Reversing string using stack

#  Stack node
class StackNode :
    #  Stack data
    def __init__(self, element, next) :
        self.element = element
        self.next = next
    

#  Define a custom stack
class MyStack :
    def __init__(self) :
        self.top = None
        self.size = 0
    
    #  Add node at the top of stack
    def push(self, element) :
        self.top = StackNode(element, self.top)
        self.size += 1
    
    def isEmpty(self) :
        if (self.size > 0 and self.top != None) :
            return False
        else :
            return True
        
    
    #  Remove top element of stack
    def pop(self) :
        if (self.size > 0 and self.top != None) :
            temp = self.top
            #  Change top element of stack
            self.top = temp.next
            self.size -= 1
        
    
    #  Return top element of stack
    def peek(self) :
        return self.top.element
    

class ReverseString :
    #  Reverse the string element
    def reverse(self, text) :
        size = len(text)
        #  Auxiliary variable which is used to store result of string
        result = ""
        #  Create an stack
        stack = MyStack()
        i = 0
        #  Add element into stack
        while (i < size) :
            #  Add element into stack
            stack.push(text[i])
            i += 1
        
        #  iterating the stack elements until if not empty
        while (stack.isEmpty() == False) :
            #  Get top element
            result += stack.peek()
            #  Remove current top
            stack.pop()
        
        return result
    

def main() :
    task = ReverseString()
    text = "This is a simple words"
    print(" Before Reverse : [", text ,"]", end = "",sep="")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]", end = "",sep="")
    text = " ABC"
    print("\n Before Reverse : [", text ,"]", end = "",sep="")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]", end = "",sep="")
    text = "BIG WIN"
    print("\n Before Reverse : [", text ,"]", end = "",sep="")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]", end = "",sep="")
    text = "BIG DOG"
    print("\n Before Reverse : [", text ,"]", end = "",sep="")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]", end = "",sep="")

if __name__ == "__main__": main()

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
#  Ruby program
#  Reversing string using stack

#  Stack node
class StackNode 
    # Define the accessor and reader of class StackNode
    attr_reader :element, :next
    attr_accessor :element, :next
    #  Stack data
    def initialize(element, n) 
        self.element = element
        self.next = n
    end

end

#  Define a custom stack
class MyStack 
    # Define the accessor and reader of class MyStack
    attr_reader :top, :size
    attr_accessor :top, :size
    def initialize() 
        self.top = nil
        self.size = 0
    end

    #  Add node at the top of stack
    def push(element) 
        self.top = StackNode.new(element, self.top)
        self.size += 1
    end

    def isEmpty() 
        if (self.size > 0 && self.top != nil) 
            return false
        else
            return true
        end

    end

    #  Remove top element of stack
    def pop() 
        if (self.size > 0 && self.top != nil) 
            temp = self.top
            #  Change top element of stack
            self.top = temp.next
            self.size -= 1
        end

    end

    #  Return top element of stack
    def peek() 
        return self.top.element
    end

end

class ReverseString 
    #  Reverse the string element
    def reverse(text) 
        size = text.length
        #  Auxiliary variable which is used to store result of string
        result = ""
        #  Create an stack
        stack = MyStack.new()
        i = 0
        #  Add element into stack
        while (i < size) 
            #  Add element into stack
            stack.push(text[i])
            i += 1
        end

        #  iterating the stack elements until if not empty
        while (stack.isEmpty() == false) 
            #  Get top element
            result += stack.peek()
            #  Remove current top
            stack.pop()
        end

        return result
    end

end

def main() 
    task = ReverseString.new()
    text = "This is a simple words"
    print(" Before Reverse : [", text ,"]")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]")
    text = " ABC"
    print("\n Before Reverse : [", text ,"]")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]")
    text = "BIG WIN"
    print("\n Before Reverse : [", text ,"]")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]")
    text = "BIG DOG"
    print("\n Before Reverse : [", text ,"]")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]")
end

main()

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
import scala.collection.mutable._;
// Scala program
// Reversing string using stack
// Stack node
class StackNode(
    // Stack data
    var element: Char,
    var next: StackNode);
// Define a custom stack
class MyStack(var top: StackNode,
    var size: Int)
{
    def this()
    {
        this(null, 0);
    }
    // Add node at the top of stack
    def push(element: Char): Unit = {
        this.top = new StackNode(element, this.top);
        this.size += 1;
    }
    def isEmpty(): Boolean = {
        if (this.size > 0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    def pop(): Unit = {
        if (this.size > 0 && this.top != null)
        {
            var temp: StackNode = this.top;
            // Change top element of stack
            this.top = temp.next;
            this.size -= 1;
        }
    }
    // Return top element of stack
    def peek(): Char = {
        return this.top.element;
    }
}
class ReverseString()
{
    // Reverse the string element
    def reverse(text: String): String = {
        var size: Int = text.length();
        // Auxiliary variable which is used to store result of string
        var result: String = "";
        // Create an stack
        var stack: MyStack = new MyStack();
        var i: Int = 0;
        // Add element into stack
        while (i < size)
        {
            // Add element into stack
            stack.push(text.charAt(i));
            i += 1;
        }
        // iterating the stack elements until if not empty
        while (stack.isEmpty() == false)
        {
            // Get top element
            result += stack.peek();
            // Remove current top
            stack.pop();
        }
        return result;
    }
}
object Main
{
    def main(args: Array[String]): Unit = {
        var task: ReverseString = new ReverseString();
        var text: String = "This is a simple words";
        print(" Before Reverse : [" + text + "]");
        text = task.reverse(text);
        print("\n After Reverse : [" + text + "]");
        text = " ABC";
        print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        print("\n After Reverse : [" + text + "]");
        text = "BIG WIN";
        print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        print("\n After Reverse : [" + text + "]");
        text = "BIG DOG";
        print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        print("\n After Reverse : [" + text + "]");
    }
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
import Foundation;
// Swift 4 program
// Reversing string using stack
// Stack node
class StackNode
{
    // Stack data
    var element: Character;
    var next: StackNode? ;
    init(_ element: Character, _ next: StackNode? )
    {
        self.element = element;
        self.next = next;
    }
}
// Define a custom stack
class MyStack
{
    var top: StackNode? ;
    var size: Int;
    init()
    {
        self.top = nil;
        self.size = 0;
    }
    // Add node at the top of stack
    func push(_ element: Character)
    {
        self.top = StackNode(element, self.top);
        self.size += 1;
    }
    func isEmpty() -> Bool
    {
        if (self.size > 0 && self.top  != nil)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    func pop()
    {
        if (self.size > 0 && self.top  != nil)
        {
            let temp: StackNode = self.top!;
            // Change top element of stack
            self.top = temp.next;
            self.size -= 1;
        }
    }
    // Return top element of stack
    func peek() -> Character
    {
        return self.top!.element;
    }
}
class ReverseString
{
    // Reverse the string element
    func reverse(_ data: String) -> String
    {
        let text = Array(data);
        let size: Int = text.count;
        // Auxiliary variable which is used to store result of string
        var result: String = "";
        // Create an stack
        let stack: MyStack = MyStack();
        var i: Int = 0;
        // Add element into stack
        while (i < size)
        {
            // Add element into stack
            stack.push(text[i]);
            i += 1;
        }
        // iterating the stack elements until if not empty
        while (stack.isEmpty() == false)
        {
            // Get top element
            result += String(stack.peek());
            // Remove current top
            stack.pop();
        }
        return result;
    }
}
func main()
{
    let task: ReverseString = ReverseString();
    var text: String = "This is a simple words";
    print(" Before Reverse : [", text ,"]", terminator: "");
    text = task.reverse(text);
    print("\n After Reverse : [", text ,"]", terminator: "");
    text = " ABC";
    print("\n Before Reverse : [", text ,"]", terminator: "");
    text = task.reverse(text);
    print("\n After Reverse : [", text ,"]", terminator: "");
    text = "BIG WIN";
    print("\n Before Reverse : [", text ,"]", terminator: "");
    text = task.reverse(text);
    print("\n After Reverse : [", text ,"]", terminator: "");
    text = "BIG DOG";
    print("\n Before Reverse : [", text ,"]", terminator: "");
    text = task.reverse(text);
    print("\n After Reverse : [", text ,"]", terminator: "");
}
main();

Output

 Before Reverse : [ This is a simple words ]
 After Reverse : [ sdrow elpmis a si sihT ]
 Before Reverse : [  ABC ]
 After Reverse : [ CBA  ]
 Before Reverse : [ BIG WIN ]
 After Reverse : [ NIW GIB ]
 Before Reverse : [ BIG DOG ]
 After Reverse : [ GOD GIB ]
// Kotlin program
// Reversing string using stack

// Stack node
class StackNode
{
    // Stack data
    var element: Char;
    var next: StackNode ? ;
    constructor(element: Char, next: StackNode ? )
    {
        this.element = element;
        this.next = next;
    }
}
// Define a custom stack
class MyStack
{
    var top: StackNode ? ;
    var size: Int;
    constructor()
    {
        this.top = null;
        this.size = 0;
    }
    // Add node at the top of stack
    fun push(element: Char): Unit
    {
        this.top = StackNode(element, this.top);
        this.size += 1;
    }
    fun isEmpty(): Boolean
    {
        if (this.size > 0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    fun pop(): Unit
    {
        if (this.size > 0 && this.top != null)
        {
            val temp: StackNode? = this.top;
            // Change top element of stack
            this.top = temp!!.next;
            this.size -= 1;
        }
    }
    // Return top element of stack
    fun peek(): Char
    {
        return this.top!!.element;
    }
}
class ReverseString
{
    // Reverse the string element
    fun reverse(text: String): String
    {
        val size: Int = text.length;
        // Auxiliary variable which is used to store result of string
        var result: String = "";
        // Create an stack
        val stack: MyStack = MyStack();
        var i: Int = 0;
        // Add element into stack
        while (i < size)
        {
            // Add element into stack
            stack.push(text.get(i));
            i += 1;
        }
        // iterating the stack elements until if not empty
        while (stack.isEmpty() == false)
        {
            // Get top element
            result += stack.peek();
            // Remove current top
            stack.pop();
        }
        return result;
    }
}
fun main(args: Array < String > ): Unit
{
    val task: ReverseString = ReverseString();
    var text: String = "This is a simple words";
    print(" Before Reverse : [" + text + "]");
    text = task.reverse(text);
    print("\n After Reverse : [" + text + "]");
    text = " ABC";
    print("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    print("\n After Reverse : [" + text + "]");
    text = "BIG WIN";
    print("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    print("\n After Reverse : [" + text + "]");
    text = "BIG DOG";
    print("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    print("\n After Reverse : [" + text + "]");
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]

The above program is large, because we are defining custom stack functionality. This is useful to understand stack functionality. Time complexity of this program is O(n).

Another way, by using of stack class.

import java.util.Stack;
// Java program
// Reversing string using inbuilt stack functionality
public class ReverseString
{
    // Reverse the string element
    public String reverse(String text)
    {
        int size = text.length();
        // Auxiliary variable which is used to store result of string
        String result = "";
        // Create an empty stack
        Stack < Character > stack = new Stack < Character > ();
        // Add element into stack
        for (int i = 0; i < size; i++)
        {
            // Add element into stack
            stack.push(text.charAt(i));
        }
        // iterating the stack elements until if not empty
        while (stack.isEmpty() == false)
        {
            // Get top element
            result += stack.peek();
            // Remove current top
            stack.pop();
        }
        return result;
    }
    public static void main(String[] args)
    {
        ReverseString task = new ReverseString();
        String text = "This is a simple words";
        System.out.print(" Before Reverse : [" + text + "]");
        text = task.reverse(text);
        System.out.print("\n After Reverse : [" + text + "]");
        text = " ABC";
        System.out.print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        System.out.print("\n After Reverse : [" + text + "]");
        text = "BIG WIN";
        System.out.print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        System.out.print("\n After Reverse : [" + text + "]");
        text = "BIG DOG";
        System.out.print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        System.out.print("\n After Reverse : [" + text + "]");
    }
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
// Include header file
#include <iostream>
#include <stack>
#include <string>

using namespace std;
// C++ program
// Reversing string using inbuilt stack functionality
class ReverseString
{
    public:
        // Reverse the string element
        string reverse(string text)
        {
            int size = text.length();
            // Auxiliary variable which is used to store result of string
            string result = "";
            // Create an empty stack
            stack < char > stack;
            // Add element into stack
            for (int i = 0; i < size; i++)
            {
                // Add element into stack
                stack.push(text[i]);
            }
            // iterating the stack elements until if not empty
            while (stack.empty() == false)
            {
                // Get top element
                result += stack.top();
                // Remove current top
                stack.pop();
            }
            return result;
        }
};
int main()
{
    ReverseString *task = new ReverseString();
    string text = "This is a simple words";
    cout << " Before Reverse : [" << text << "]";
    text = task->reverse(text);
    cout << "\n After Reverse : [" << text << "]";
    text = " ABC";
    cout << "\n Before Reverse : [" << text << "]";
    text = task->reverse(text);
    cout << "\n After Reverse : [" << text << "]";
    text = "BIG WIN";
    cout << "\n Before Reverse : [" << text << "]";
    text = task->reverse(text);
    cout << "\n After Reverse : [" << text << "]";
    text = "BIG DOG";
    cout << "\n Before Reverse : [" << text << "]";
    text = task->reverse(text);
    cout << "\n After Reverse : [" << text << "]";
    return 0;
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
// Include namespace system
using System;
using System.Collections.Generic;
// Csharp program
// Reversing string using inbuilt stack functionality
public class ReverseString
{
    // Reverse the string element
    public String reverse(String text)
    {
        int size = text.Length;
        // Auxiliary variable which is used to store result of string
        String result = "";
        // Create an empty stack
        Stack < char > stack = new Stack < char > ();
        // Add element into stack
        for (int i = 0; i < size; i++)
        {
            // Add element into stack
            stack.Push(text[i]);
        }
        // iterating the stack elements until if not empty
        while ((stack.Count == 0) == false)
        {
            // Get top element
            result += stack.Peek();
            // Remove current top
            stack.Pop();
        }
        return result;
    }
    public static void Main(String[] args)
    {
        ReverseString task = new ReverseString();
        String text = "This is a simple words";
        Console.Write(" Before Reverse : [" + text + "]");
        text = task.reverse(text);
        Console.Write("\n After Reverse : [" + text + "]");
        text = " ABC";
        Console.Write("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        Console.Write("\n After Reverse : [" + text + "]");
        text = "BIG WIN";
        Console.Write("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        Console.Write("\n After Reverse : [" + text + "]");
        text = "BIG DOG";
        Console.Write("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        Console.Write("\n After Reverse : [" + text + "]");
    }
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
#  Python 3 program
#  Reversing string using inbuilt list functionality
class ReverseString :
    #  Reverse the string element
    def reverse(self, text) :
        size = len(text)
        #  Auxiliary variable which is used to store result of string
        result = ""
        #  Create an empty stack
        stack = []
        i = 0
        #  Add element into stack
        while (i < size) :
            #  Add element into stack
            stack.append(text[i])
            i += 1
        
        #  iterating the stack elements until if not empty
        while ((len(stack) == 0) == False) :
            #  Get top element
            result += stack[-1]
            #  Remove current top
            stack.pop()
        
        return result
    

def main() :
    task = ReverseString()
    text = "This is a simple words"
    print(" Before Reverse : [", text ,"]", end = "")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]", end = "")
    text = " ABC"
    print("\n Before Reverse : [", text ,"]", end = "")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]", end = "")
    text = "BIG WIN"
    print("\n Before Reverse : [", text ,"]", end = "")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]", end = "")
    text = "BIG DOG"
    print("\n Before Reverse : [", text ,"]", end = "")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]", end = "")

if __name__ == "__main__": main()

Output

 Before Reverse : [ This is a simple words ]
 After Reverse : [ sdrow elpmis a si sihT ]
 Before Reverse : [  ABC ]
 After Reverse : [ CBA  ]
 Before Reverse : [ BIG WIN ]
 After Reverse : [ NIW GIB ]
 Before Reverse : [ BIG DOG ]
 After Reverse : [ GOD GIB ]
#  Ruby program
#  Reversing string using inbuilt stack functionality
class ReverseString 
    #  Reverse the string element
    def reverse(text) 
        size = text.length
        #  Auxiliary variable which is used to store result of string
        result = ""
        #  Create an empty stack
        stack = []
        i = 0
        #  Add element into stack
        while (i < size) 
            #  Add element into stack
            stack.push(text[i])
            i += 1
        end

        #  iterating the stack elements until if not empty
        while ((stack.length == 0) == false) 
            #  Get top element
            result += stack.last
            #  Remove current top
            stack.pop()
        end

        return result
    end

end

def main() 
    task = ReverseString.new()
    text = "This is a simple words"
    print(" Before Reverse : [", text ,"]")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]")
    text = " ABC"
    print("\n Before Reverse : [", text ,"]")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]")
    text = "BIG WIN"
    print("\n Before Reverse : [", text ,"]")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]")
    text = "BIG DOG"
    print("\n Before Reverse : [", text ,"]")
    text = task.reverse(text)
    print("\n After Reverse : [", text ,"]")
end

main()

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
import scala.collection.mutable._;
// Scala program
// Reversing string using inbuilt stack functionality
class ReverseString()
{
    // Reverse the string element
    def reverse(text: String): String = {
        var size: Int = text.length();
        // Auxiliary variable which is used to store result of string
        var result: String = "";
        // Create an empty stack
        var stack: Stack[Character] = new Stack[Character]();
        var i: Int = 0;
        // Add element into stack
        while (i < size)
        {
            // Add element into stack
            stack.push(text.charAt(i));
            i += 1;
        }
        // iterating the stack elements until if not empty
        while (stack.isEmpty == false)
        {
            // Get top element
            result += stack.top;
            // Remove current top
            stack.pop;
        }
        return result;
    }
}
object Main
{
    def main(args: Array[String]): Unit = {
        var task: ReverseString = new ReverseString();
        var text: String = "This is a simple words";
        print(" Before Reverse : [" + text + "]");
        text = task.reverse(text);
        print("\n After Reverse : [" + text + "]");
        text = " ABC";
        print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        print("\n After Reverse : [" + text + "]");
        text = "BIG WIN";
        print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        print("\n After Reverse : [" + text + "]");
        text = "BIG DOG";
        print("\n Before Reverse : [" + text + "]");
        text = task.reverse(text);
        print("\n After Reverse : [" + text + "]");
    }
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]
import java.util.Stack;
// Kotlin program
// Reversing string using inbuilt stack functionality
class ReverseString
{
    // Reverse the string element
    fun reverse(text: String): String 
    {
        val size: Int = text.length;
        // Auxiliary variable which is used to store result of string
        var result: String = "";
        // Create an empty stack
        val stack: Stack < Char > = Stack < Char > ();
        var i: Int = 0;
        // Add element into stack
        while (i < size)
        {
            // Add element into stack
            stack.push(text.get(i));
            i += 1;
        }
        // iterating the stack elements until if not empty
        while (stack.empty() == false)
        {
            // Get top element
            result += stack.peek();
            // Remove current top
            stack.pop();
        }
        return result;
    }
}
fun main(args: Array < String > ): Unit
{
    val task: ReverseString = ReverseString();
    var text: String = "This is a simple words";
    print(" Before Reverse : [" + text + "]");
    text = task.reverse(text);
    print("\n After Reverse : [" + text + "]");
    text = " ABC";
    print("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    print("\n After Reverse : [" + text + "]");
    text = "BIG WIN";
    print("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    print("\n After Reverse : [" + text + "]");
    text = "BIG DOG";
    print("\n Before Reverse : [" + text + "]");
    text = task.reverse(text);
    print("\n After Reverse : [" + text + "]");
}

Output

 Before Reverse : [This is a simple words]
 After Reverse : [sdrow elpmis a si sihT]
 Before Reverse : [ ABC]
 After Reverse : [CBA ]
 Before Reverse : [BIG WIN]
 After Reverse : [NIW GIB]
 Before Reverse : [BIG DOG]
 After Reverse : [GOD GIB]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved