April 1999
CA208: 'C' PROGRAMMING

QUESTION 4

Total Marks: 20 Marks

Click here to access other questions

GRADE A
Sample student's solutions are indicated in green.
Return to Question 4

 

(a) Assume the following definition of a linear linked list as the representation of the elements of a stack:

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

typedef struct {
  StackElement *top_of_stack;
} StackType;

 

(i) Write a procedure, push -  which has the procedure prototype shown below - that will push element x onto the stack stack.

void push(StackType *stack, int x);

[4]
(i)
void push(StackType stack, int x)
{   StackElement *Temp;
    Temp = (StackElement*) malloc(size of (StackElement));
    Temp->data = x;
    Temp-> next = stack.top_of_stack;
    stack.top_of_stack=Temp;
}

 

(ii) Write a function, isempty - which has the function prototype shown below - that will return 1 if the stack stack is empty, and will return 0 otherwise.

int isempty(StackType stack);

[2]
(ii)

int isempty (StackType stack)
         return ( stack.top_of_stack == NULL);

 

(iii) Write a function, sizeStack - which has the function prototype shown below - that will return the number of element in the stack stack.

int sizeStack(StackType stack);

[4]
(iii)

int sizeStack(StackType stack)
     {   int count = 0;
         StackElement *Temp;
         Temp = stack.top_of_stack;
         While (Temp !=NULL)
         {    count ++;
              Temp = Temp->next;
         }
        return count;
    }

 

(iv) Write a procedure, pop - which has the procedure prototype shown below - that will return and then remove the top element from the stack stack. You should call the procedure error (with prototype given below) if it is not possible to remove an element from the stack.

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

Note: You are not required to write the error procedure.

[5]
(iv)

void pop(StackType stack)
{   StackElement *Temp;
    if (stack.top_of_stack == NULL)
             error();
    else
    {    Temp = stack.top_of_stack;
         stack.top_of_stack = Temp->next;
         free (Temp);
     }
}  
          

(b) Trace the following code segment and write down the output produced:

typedef struct {
  int a;
  int *p;
} PairType;

void main(void) {
  PairType x, y, *z;
  int i = 1972;

  x.a = 42;
  x.p = &i;
  z = &x;
  (*(z->p))++;

  y.a=1999;
  y.p=&(y.a);
  (*(y.p))++;

  printf("x.a = %d\n", x.a);
  printf("i = %d\n", i);
  printf("*(x.p) = %d\n", *(x.p));
  printf("y.a = %d\n", y.a);
  printf("*(y.p) = %d\n", *(y.p));
}

(b)

x.a=42
i=1973
*(x.p) = 1973
y.a = 2000
*(y.p) = 2000