So I have yet to take the data structures course at my university but I was asked for help by someone who is in said class so I decided to take a look and see what I could come up with code wise.
The original assignment was supposed to be in Java with a GUI for pushing and popping as well as to display the current stack. I decided to try my had at doing it in C with stdio first since that is what I am more familiar with and this is what I came up with.
Code:
This is entirely my own code I came up with after trying to help my friend started with his java. Other than checking if malloc is actually returning a pointer and not null, is there anything else you would suggest or a better way to handle things?
I also have a similar program for a doubly linked list implementing a queue but the code is so similar its not really worth posting. So again, thoughts suggestions, things I missed?
The original assignment was supposed to be in Java with a GUI for pushing and popping as well as to display the current stack. I decided to try my had at doing it in C with stdio first since that is what I am more familiar with and this is what I came up with.
Code:
#include <stdio.h>
#include <stdlib.h>
struct Item {
int val;
struct Item *next;
struct Item *last;
}Item;
static struct Item *head =NULL;
static struct Item *tail =NULL;
static void push(int value) {
struct Item *tmp;
tmp = malloc(sizeof(Item));
tmp->val = value;
if (head==NULL) {
tail = head = tmp;
tmp->next=NULL;
tmp->last=NULL;
}
tail->next = tmp;
tmp->last = tail;
tail = tmp;
}
static int pop() {
int ret;
if (head == NULL) {
return 0;
}
struct Item *tmp;
ret = tail->val;
tmp = tail;
if (tail->last != tail){
tail = tail->last;
}else {
tail = head =NULL;
}
free(tmp);
return ret;
}
static void printList() {
struct Item *tmp =head;
printf("Stack = [");
while (tmp != tail) {
printf(" %i,", tmp->val);
tmp = tmp->next;
}
printf(" %i]\n",tmp->val);
}
static int peekHead() {
if (head != NULL) {
return head->val;
}
return 0;
}
static int peekTail() {
if (tail != NULL) {
return tail->val;
}
return 0;
}
int main(void) {
int i,j,k;
scanf("%i", &i);
printf("Will Push %i values.\n",i);
for (j=0;j<i;j++) {
scanf("%i", &k);
push(k);
printf("Pushed %i\n",tail->val);
}
printf("head value = %i\n",peekHead());
printList();
printf("tail value = %i\n",peekTail());
for (j=0;j<(i+1);j++) {
k=pop(k);
printf("Popped %i\n",k);
}
return 0;
}
This is entirely my own code I came up with after trying to help my friend started with his java. Other than checking if malloc is actually returning a pointer and not null, is there anything else you would suggest or a better way to handle things?
I also have a similar program for a doubly linked list implementing a queue but the code is so similar its not really worth posting. So again, thoughts suggestions, things I missed?