From b056321f3a322b14ea007bfc47e49715736bb04b Mon Sep 17 00:00:00 2001 From: Spark <43844351+keepmine@users.noreply.github.com> Date: Fri, 8 Mar 2019 22:18:09 +0800 Subject: [PATCH] Update stack.c I think you should test the top before swap the two top elements --- Chapter4/Exercise 4-04/stack.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Chapter4/Exercise 4-04/stack.c b/Chapter4/Exercise 4-04/stack.c index 6ea7ad3..6c03606 100644 --- a/Chapter4/Exercise 4-04/stack.c +++ b/Chapter4/Exercise 4-04/stack.c @@ -76,15 +76,21 @@ void duplicate(void) /* swap: swap the top two elements of the stack */ void swap(void) -{ - double top1 = pop(); - double top2 = pop(); - push(top1); - push(top2); + { + double top1; + double top2; + if (top > 1) { + top1 = pop(); + top2 = pop(); + push(top1); + push(top2); + } + else + printf("erorr: there is only one or no element in stack\n"); } /* clear: clear stack */ void clear(void) { sp = 0; -} \ No newline at end of file +}