December 1998
CA208: 'C' PROGRAMMING

QUESTION 5

Total Marks: 20 Marks

Click here to access other questions

Click to access
SUGGESTED SOLUTIONS
for Question 5

 

(a) Give the following definition of a linear linked-list type as the representation of the elements in a stack,

typedef struct stack_element {
    int data;
    struct stack_element *next;
} StackElement;

typedef struct {
    StackElement *top_of_stack:
} StackType;

The following questions require the definition of a series of functions that form an interface to a stack. You can assume that the stack argument to each of the functions is a non-null pointer, and points to a valid StackType.

 

[2]
(a) Write a function isempty, that has the function prototype shown below, that returns a one if stack is empty, and zero otherwise.

int isempty(StackType *stack);

 

[2]
(b) Write a procedure push, that has the procedure prototype shown below, that pushes the element x onto the stack stack. You assume that stack will always be a non-null pointer to a valid StackType.

void push(StackType *stack, int x);

 

[4]
(c) Write a function pop, that has the function prototype shown below, that returns and then removes the top element from the stack stack. You should call the function error (with prototype below), if it is not possible to remove an element from the stack.

int pop(StackType *stack);
void error(void);

 

[5]
(d) Write a function concatenate, that has the function prototype shown below, that joins the two stacks left and right together. i.e., if left contained the sequence [1,2,3] and right [4,5], then the function should alter left so that it represents the sequence [1,2,3,4,5].

void concatenate(StackType *left, StackType *right)

 

[5]
(e) Using the function pop and isempty defined below, define a procedure popmany, that has the function prototype shown below, that removes the top n items from the stack, if the stack contains at least n items; otherwise all items are removed from the stack.

void popmany(StackType *stack, int n)

[4]