Stack

C++ vs Python vs Rust

C++ Rust Python Go
Declaration
    
stack<int> st;
    
let mut stack: Vec = Vec::new();
    
Python doesn't have built-in Stack.
Its implemented using a list.
st = []
Go doesn't have a built-in stack data structure like C++
stack in Go is implemented using a slice.

type Stack struct {
    vals []int
}
                
Empty
               
!st.empty()
               
self.s1.is_empty()                
               
len(st)
Method Reciever (s *Stack)
(s *Stack) before the function name is a method receiver.
This associates the function to Stack type & allows the method to access/modify the Stack member variables.
Similar to how you we define method in class in C++ or Java

func (o *Stack)IsEmpty() bool {
    if len(o.vals) == 0 {
        return true
    }
    return false
}
            
Last
               
st.back()
               
//pub fn last(&self) -> Option<&T>
if let Some(&ele) = self.s1.last() {
    
}                
               
            


Pop
               
st.pop()
               
if let Some(ele) = self.s1.pop() {
    //ele removed
}
               
st.pop()
if array size>0, store 1 less element from back

func (o *Stack)Pop() {
    if len(o.val) > 0 {
        o.val = o.val[:len(o.val)-1]
    }
}

//a= [1,2,3,4,5]
a = a[:4]   //1,2,3,4
push
               
st.push(a)
               
self.s1.push(x);
               
st.append(item)
Push element at end of slice and store back into vals

func (o *Stack)Push(item int) {
    o.vals = append(o.vals, item)
}
Top
           
st.top()
               
self.st.last()
               
st[-1]
                
func (o *Stack)Top() int {
    if len(o.val) > 0 {
        return o.val[len(o.val)-1]
    }
    return 0
}