Thread: Stack manipulation

  1. #1
    JJD
    Guest

    Stack manipulation

    I am an advanced beginner c I am given a stack/push/pop assignement to do but I have no clue on how to do it. The book that I have sucks in explaining stacks and old threads in here are too complicated or advanced for me right now.

    I am given this outline to go by:
    Code:
    for(;;)
    {
       fgets(command,sizeof(command), stdin);
       if(feof(stdin))break;
       if(command[0]=='p') push atoi (command+1) onto stack
       if(command[0]=='w') pop number from stack
    
       display contents of the stack
    }
    So I I want to ad 5678 to a stack I have to be able to write at the command: p 5678 or w 5678 to remove it from the stack


    Please need help!!

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    >I am an advanced beginner

    Ehm, ok.

    A stack is a piece of memory which works according to the LIFO principe, data which is stored last will be retrieved first. There are two basic functions on stacks, push and pop. Push pushes data onto the stack and pop gets data from the stack.

    Example:

    An empty stack:
    stack = []

    Put data on stack
    push (stack, 1)

    The stack is now:
    stack = [1]

    Put more data on stack
    push (stack, 2)

    The stack is now:
    stack = [1, 2]

    Get data from stack
    value = pop (stack)

    Now:
    value = 2
    stack = [1]

    So you could for example declare an array of size N and define push and pop functions onto it.

    You could implement it something like this pseudo-code. But note that in this pseudo-code there is not taken care of the maximum size of the stack.

    Code:
    int stack [N]
    
    function push (stack, variable)
    begin
        top = top + 1
        stack [top] = variable
    end
    
    function pop (stack)
    begin
        value = stack [top]
        top = top - 1
        return value
    end

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stack and pointer problem
    By ramaadhitia in forum C Programming
    Replies: 2
    Last Post: 09-11-2006, 11:41 PM
  2. Question about a stack using array of pointers
    By Ricochet in forum C++ Programming
    Replies: 6
    Last Post: 11-17-2003, 10:12 PM
  3. error trying to compile stack program
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-03-2003, 06:27 PM
  4. What am I doing wrong, stack?
    By TeenyTig in forum C Programming
    Replies: 2
    Last Post: 05-27-2002, 02:12 PM
  5. Stack Program Here
    By Troll_King in forum C Programming
    Replies: 7
    Last Post: 10-15-2001, 05:36 PM