First Implementation

We shall tie together the ideas discussed previously by showing a first cut at the implementation of the int_stack type.
Warning:This is not the final or recommended code.


	/* This is the actual implementation */
	int_stack
	make_int_stack(void)
	{
	  int_stack	stack = malloc(sizeof(struct int_stack));
	  x_max_int_stack(stack) = 16;
	  x_len_int_stack(stack) = 0;
	  x_vals_int_stack(stack) = malloc(16*sizeof(int));
	  return stack;
	}

	void
	destroy_int_stack(
		int_stack	stack
		)
	{
	  free(vals_int_stack(stack));
	  free(stack);
	}

	void
	push_int_stack(
		int_stack	stack,
		int		val
		)
	{
	  int	len = len_int_stack(stack);
	  int	max = max_int_stack(stack);
	  int	nmax;
	  int *	vals;
	  int *	nvals;
	  int	i;

	  if( len == max ) {
	    nmax = max + 16;
	    nvals = malloc(nmax*sizeof(int));
	    vals = vals_int_stack(stack);
	    for( i = 0; i < len; i++ ) {
	      nvals[i] = vals[i];
	    }
	    x_max_int_stack(stack) = nmax;
	    x_vals_int_stack(stack) = nvals;
	    free(vals);
	  }

	  vals_int_stack(stack)[len] = val;
	  x_len_int_stack(stack) = len+1;
	}

	void
	pop_int_stack(
		int_stack	stack
		)
	{
	  x_len_int_stack(stack)--;
	}

	int
	top_int_stack(
		const int_stack	stack
		)
	{
	  return vals_int_stack(stack)[len_int_stack(stack)-1];
	}

	int
	is_empty_int_stack(
		const int_stack stack
		)
	{
	  return len_int_stack(stack) == 0;
	}

Note that there are several discrepancies with respect to the final code:


Next Prev Main Top Feedback