Stack implementation in C producing confusing results - c

For a component of an assignment for college we have to implement a stack, which I think I've done well enough for it to be functional. When I'm testing the stack by itself it seems to work fine, however when I'm using it as part of my solution it behaves differently, and I can't figure out why. Can someone please point out my mistake? Thanks.
Edit: I can feel a lot of "how does it behave differently?" comments are on the way, so here's what I've noticed. When running the Testing stack section of main, all the operations execute and print perfectly fine, but when I'm running the second part of main and comment out the testing part instead, the program crashes when I'm trying to push onto the stack - something that didn't fail previously.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
struct stackNode {
char data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;
typedef enum {
false, true
} t_bool;
void* emalloc(size_t s) {
void* p = malloc(s);
if (NULL == p) {
fprintf(stderr, "Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
return p;
}
void print_array(char* array, size_t n){
int i;
printf("[");
for(i = 0; i < n - 1; i++){
printf("%c, ", array[i]);
}
printf("%c]\n", array[i]);
}
// Determine if c is an operator.
int isOperator(char c) {
char ops [6] = {'+', '-', '*', '/', '%', '^'};
int i;
for (i = 0; i < 6; i++)
if (ops[i] == c) return true;
return false;
}
int op_priority(char c) {
if (c == '+' || c == '-') return 0;
else if (c == '*' || c == '/') return 1;
else if (c == '^' || c == '%') return 2;
return -1;
}
// Determine if the precedence of operator1 is less than, equal to, or greater than
// the precedence of operator2. The function returns -1, 0 and 1, respectively.
int precedence(char op1, char op2) {
int op1_p = op_priority(op1);
int op2_p = op_priority(op2);
if (op1_p < op2_p) return -1;
else if (op1_p > op2_p) return 1;
else return 0;
}
// Push a value on the stack.
void push(StackNodePtr *topPtr, char value) {
StackNodePtr temp = (StackNodePtr) emalloc(sizeof (StackNode));
temp->data = value;
temp->nextPtr = *topPtr;
*topPtr = temp;
}
// Pop a value off the stack.
char pop(StackNodePtr *topPtr) {
StackNodePtr t = *topPtr;
if (NULL != *topPtr) {
char c = t->data;
*topPtr = t->nextPtr;
free(t);
return c;
} else {
printf("Stack is empty.\n");
return '\0';
}
}
// Return the top value of the stack without popping the stack.
char peek(StackNodePtr topPtr) {
if (NULL != topPtr) {
return topPtr->data;
} else {
printf("Stack is empty.\n");
}
}
// Determine if the stack is empty.
int isEmpty(StackNodePtr topPtr) {
if (NULL == topPtr) return true;
return false;
}
// Prints the stack
void printStack(StackNodePtr topPtr) {
if (!isEmpty(topPtr)){
StackNodePtr t = topPtr;
while (NULL != t) {
printf("%c\t", t->data);
t = t->nextPtr;
}
printf("NULL\n");
} else {
printf("Stack is empty.\n");
}
}
// Convert the infix expression to postfix notation.
void convertToPostfix(char infix [], char postfix [], int expression_length) {
printf("At top of cnvToPostfix\n");
int infix_count = 0;
int postfix_count = 0;
////////////////////////////////////////////
StackNodePtr *stack;
push(stack, '(');
printStack(*stack);
////////////////////////////////////////////
infix[expression_length] = ')';
while (isEmpty(*stack)) {
char current = infix[infix_count++];
if (isdigit(current)) {
postfix[postfix_count++] = current;
} else if (current == '(') {
push(stack, current);
} else if (isOperator(current)) {
while (true) {
char top = peek(*stack);
if (isOperator(top) && precedence(current, top) >= 0) {
postfix[postfix_count++] = pop(stack);
} else {
break;
}
}
push(stack, current);
}
else if (current == ')') {
while (true) {
char top = peek(*stack);
if (top == '(') {
pop(stack);
break;
} else {
postfix[postfix_count++] = pop(stack);
}
}
}
}
}
int main() {
printf("Testing stack\n");
printf("Pushing 1, 2, and 3 onto stack, peeking and popping.\n");
StackNodePtr *stack;
push(stack, '1');
push(stack, '2');
push(stack, '3');
printf("Printing stack\n\n");
printStack(*stack);
printf("Peek: %c\n", peek(*stack));
printf("Pop: %c\n", pop(stack));
printf("Printing stack\n");
printStack(*stack);
/*
printf("Enter the infix expression.\n");
char c;
char infix [1024];
int count = 0;
while ((scanf("%c", &c)) == 1) {
if ((int) c == 10) break;
infix[count++] = c;
}
printf("The original infix expression is:\n");
print_array(infix, count);
char postfix [count];
convertToPostfix(infix, postfix, count);
printf("The expression in postfix notation is:\n");
print_array(postfix, count);
*/
return 0;
}

I see at least one immediate problem:
StackNodePtr *stack;
push(stack, '1');
Where is the initialisation for your stack? Use of uninitialised pointers is instant "undefined behaviour" territory.
If you look closely at your push code, you'll see it inserts the new item before the current one but set the new item's nextPtr pointer to the previous (uninitialised) value.
That means, the last item in the stack won't actually point to NULL.

You're not really initialising your stacks:
StackNodePtr *stack;
push(stack, '(');
It's also potentially confusing having StackNodePtr being a pointer type, and stack being a pointer to that type. You need to be clear in every possible usage how many levels of indirection should be applied.
To start with, imagine passing the new stack firstly to isEmpty:
StackNodePtr *stack;
printf("%d\n", isEmptypush(*stack));
What's isEmpty going to do on the value it is passed?
I think what you want instead is:
StackNodePtr stack = NULL;
push(&stack, '(');
Other uses of stack in that function should similarly be changed from *stack to stack, or stack to &stack.

Related

Balanced Brackets Checker always gives incorrect output

I have created a function which uses Linked List to check whether an expression is balanced or not. A balanced expression has no. of opening brackets equal to no. of closing brackets.
But the function Bracket Balancing always gives "unbalanced" as the output.
CODE:
#include <stdio.h>
#include <stdlib.h>
struct LL {
char data;
struct LL *next;
};
int isEmpty(struct LL *top) {
if (top == NULL) {
return 1;
}
else {
return 0;
}
}
int isFull(struct LL *top) {
struct LL *n = malloc(sizeof(struct LL *));
if (n == NULL) {
return 1;
}
else {
return 0;
}
}
struct LL *push(struct LL *top, char x) {
if (isFull(top)) {
printf("Stack Overflow\n");
}
else {
struct LL *n = malloc(sizeof(struct LL));
n->data = x;
n->next = top;
top = n;
}
return top;
}
struct LL *pop(struct LL *top) {
if (isEmpty(top)) {
printf("Stack Underflow\n");
}
else {
struct LL *n = malloc(sizeof(struct LL));
n = top;
top = top->next;
free(n);
}
return top;
}
int BracketBalancing (char *exp) {
struct LL *top = malloc(sizeof(struct LL));
top->next = NULL;
for (int i = 0; exp[i] != '\0'; i++) {
if (exp[i] == '(') {
push(top, exp[i]);
}
else if (exp[i] == ')') {
if (isEmpty(top)) {
return 0;
}
pop(top);
}
}
if (isEmpty(top)) {
return 1;
}
else {
return 0;
}
}
MAIN:
int main(int argc, char const *argv[]) {
int n;
char *expression = (char *)malloc(sizeof(char));
printf("Enter the length of the expression for Bracket Balancing\n");
scanf("%d", &n);
printf("Enter the expression for Bracket Balancing\n");
for (int i = 0; i < n; i++) {
scanf("%c ", &expression[i]);
}
getchar();
if (BracketBalancing(expression)) {
printf("The expression is balanced\n");
}
else if (!BracketBalancing(expression)) {
printf("This expression is unbalanced\n");
}
return 0;
}
Example:
Input:
Enter the length of the expression for Bracket Balancing
4
Enter the expression for Bracket Balancing
1+()
Output:
This expression is unbalanced
In the above example, Despite the expression being balanced the output generated is "This expression is unbalanced".
Please correct my code.
This is how you initialize your list:
struct LL *top = malloc(sizeof(struct LL));
top->next = NULL;
And this is isEmpty():
int isEmpty(struct LL *top)
{
if (top == NULL)
{
return 1;
}
else
{
return 0;
}
}
But: top starts with a value != NULL, so isEmtpy() will not return 1, although our list should be empty in the beginning.
Your implementation of push() should work fine when you pass NULL, so you can just initialize struct LL *top = NULL; instead of creating the first element rightaway.
there other bugs in your code, e.g.:
in pop() you do
struct LL *n = malloc(sizeof(struct LL));
n = top;
thus, the result of malloc() is directly overwritten() in the next line
in isFull() you produce a memory leak as you call malloc() and never use or free() the buffer returned. That function doesn't make sense anyway, just check the result of malloc()s where your really want to use the buffer returned.
** Edit **
What I haven't seen before, you also never use the return value of push() and pop() so the new top determined by these function is lost. Replace push(top, ...); by top = push(top,...); and pop(top); by top = pop(top);

Stack in C, converting infix with postfix

I'm trying to implement a stack in C to convert infix to postfix. But after several days of trying, im still not sure whats wrong with my code! can someone help? I made sure the line of logic is right and did on paper a lot of times, I'm new to stack, please assist!
I'm not sure exactly where is going wrong, and after a few submissions, suddenly the same code would produce segmentation error (core dumped) without much explanation.
Examples of inputs like : (A+B)+(C-D) produces (AB)+(C+D)- As for debuggers, im sticking to simple print statements at various parts of the program, I find that theres a problem with popping the '(' at the else if (infix == ')')
Running the code in online IDEs like replit and codechef. replit produces segmentation fault(core dumped) while codechef is able to produce and run an output. <- abit confused here
EDIT: My parenthesis Else if statements arent working, but I dont see why so, I tried adding simple print statements in that else if segments but they are not showing too
#include <stdio.h>
#include <stdlib.h>
#define SIZE 1000 //The limit of expression length
typedef struct _stackNode{
char item;
struct _stackNode *next;
}StackNode;
typedef struct _stack{
int size;
StackNode *head;
}Stack;
void push(Stack *sPtr, char item);
int pop(Stack *sPtr);
char peek(Stack s);
int isEmptyStack(Stack s);
void in2Post(char*, char*);
int main()
{
char infix[SIZE];
char postfix[SIZE];
printf("Enter an infix expression:\n");
scanf("%[^\n]%*c",infix);
printf("This");
in2Post(infix,postfix);
printf("The postfix expression is \n");
printf("%s\n",postfix);
return 0;
}
void push(Stack *sPtr, char item){
StackNode *newNode;
newNode = (StackNode *) malloc(sizeof(StackNode));
newNode->item = item;
newNode->next = sPtr->head;
sPtr->head = newNode;
sPtr->size++;
}
int pop(Stack *sPtr){
if(sPtr == NULL || sPtr->head == NULL){
return 0;
}
else{
StackNode *temp = sPtr->head;
sPtr->head = sPtr->head->next;
free(temp);
sPtr->size--;
return 1;
}
}
char peek(Stack s){
return s.head->item;
}
int isEmptyStack(Stack s){
if(s.size == 0) return 1;
else return 0;
}
int precedence(char item)
{
if (item == '*' || item == '/')
{
return 2;
}
else if (item == '+' || item == '-')
{
return 1;
}
else
{
return 0; // if it is brackets return 0
}
}
int isOperand(char ch)
{
if (ch == '%' || ch == '/' || ch == '*' || ch == '+' || ch == '-')
{
return 0;
}
else
{
return 1;
}
}
int is_operator(char item)
{
if (item == '+' || item == '-' || item == '*' || item == '/')
{
return 1;
}
else
{
return 0;
}
}
void in2Post(char* infix, char* postfix)
{
//Write your code here
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->head = NULL;
if (!stack)
return;
int i = 0;
int j = 0;
while (infix[i] != '\0')
{
if (isOperand(infix[i]) && infix[i] != ')' && infix[i] != '(') //NEED TO MAKE SURE HERE ISNT A PARENTHESIS
{
postfix[j]=infix[i];
j++;
}
else if (infix[i] == '(')
{
push(stack, infix[i]);
}
else if (infix[i] == ')')
{
while (!isEmptyStack(*stack) && peek(*stack) != '(')
{
postfix[j] = peek(*stack);
j++;
pop(stack);
if (!isEmptyStack(*stack) && peek(*stack) !='(' )
{
return; // POPPING TILL REACH '(' IF IT IS NOT '(', RETURN
}
else
{
pop(stack); // removing the ()
}
}
}
else // an OPERATOR IS ENCOUNTERED
{
while (!isEmptyStack(*stack) && precedence(infix[i])<=precedence(peek(*stack)))
{
postfix[j] = peek(*stack);
pop(stack);
j++;
}
push(stack, infix[i]);
}
i++;
}
while (!isEmptyStack(*stack))
{
postfix[j] = peek(*stack);
pop(stack);
j++;
}
postfix[j] = '\0';
printf("THIS IS POSTFIX %s\n", postfix);
}
The first IF statement did not take into account the character might be a parenthesis. Also, the size of the stack is not initialized.

memory allocation to stack pointer

my code is not working but when I change struct stack *sp; to struct stack * sp = (struct stack *) malloc(sizeof(struct stack)); it start working. I am confused in when to allocate memory in heap to struct stack *ptr and when to not. It will be better if u can give me an example when struct stack *ptr can be used and when to use struct stack * sp = (struct stack *) malloc(sizeof(struct stack));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
int size;
int top;
char *arr;
};
int stackTop(struct stack* sp){
return sp->arr[sp->top];
}
int isEmpty(struct stack *ptr)
{
if (ptr->top == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size - 1)
{
return 1;
}
else
{
return 0;
}
}
void push(struct stack* ptr, char val){
if(isFull(ptr)){
printf("Stack Overflow! Cannot push %d to the stack\n", val);
}
else{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
char pop(struct stack* ptr){
if(isEmpty(ptr)){
printf("Stack Underflow! Cannot pop from the stack\n");
return -1;
}
else{
char val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
}
int precedence(char ch){
if(ch == '*' || ch=='/')
return 3;
else if(ch == '+' || ch=='-')
return 2;
else
return 0;
}
int isOperator(char ch){
if(ch=='+' || ch=='-' ||ch=='*' || ch=='/')
return 1;
else
return 0;
}
char* infixToPostfix(char* infix){
struct stack *sp;
sp->size = 10;
sp->top = -1;
sp->arr = (char *) malloc(sp->size * sizeof(char));
char * postfix = (char *) malloc((strlen(infix)+1) * sizeof(char));
int i=0; // Track infix traversal
int j = 0; // Track postfix addition
while (infix[i]!='\0')
{
if(!isOperator(infix[i])){
postfix[j] = infix[i];
j++;
i++;
}
else{
if(precedence(infix[i])> precedence(stackTop(sp))){
push(sp, infix[i]);
i++;
}
else{
postfix[j] = pop(sp);
j++;
}
}
}
while (!isEmpty(sp))
{
postfix[j] = pop(sp);
j++;
}
postfix[j] = '\0';
return postfix;
}
int main()
{
char * infix = "x-y/z-k*d";
printf("postfix is %s", infixToPostfix(infix));
return 0;
}
Two things to always remember when working with pointers in C:
Memory allocation is your problem. You have to think about the allocation of the memory which a pointer variable points to.
You have to be clear in your mind about the distinction between the pointer versus the data that it points to.
So when you say
struct stack *sp;
that will never work, all by itself. It won't work for a program that's implementing a stack, and it won't work for a program that's implementing any other kind of data structure.
When you write
struct stack *sp;
there is one important thing that you have done, and there is one important thing that you have not done.
The compiler allocates space to store one pointer. This pointer is known as sp. But:
The value of this pointer is indeterminate, which means that it does not point anywhere yet. You can't actually use the pointer variable sp for anything. (Yet.)
Or, in other words, going back to the distinction I mentioned earlier, you have taken care of the pointer but you don't have any data that the pointer points to.
But when you say
sp = malloc(sizeof(struct stack));
(and assuming malloc succeeds), now sp points somewhere: it points to a chunk of properly-allocated memory sufficient to hold one struct stack.

NULL pointer gets randomly modified to 0x62 or similar

I'm making a regex parser. The instruction "t->left = tmp;" the instruction "t->left = tmp;" creates a segmentation fault, but not always ! Try executing the code several times, you'll see that it doesn't always happen. The segmentation fault occurs when printing the tree, because one of the nodes has a child with address "0x62" or "0x54" or something similar. It's really weird because when "tmp" is created I check that both children are NULL but somehow one of them gets modified to "0x.." while executing.
Thanks to anyone that could help me solve this !
I spent quite a while trying to figure out why just adding a "left children" while parsing the tree will create a segmentation fault. I really don't understand because it's a simple pointer creation and assignment ! Comment the instruction "t->left = tmp;" and the segmentation fault is gone ! The weirdest issue so far..
Best regards !
/*
* Includes
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Typedefs
*/
struct node {
char val;
struct node* left;
struct node* right;
};
typedef struct node NODE;
typedef struct node * TREE;
/*
* Tree handling
* - create
* - free
* - print
*/
TREE createNode(char val) {
TREE t = (TREE) malloc(sizeof(TREE));
t->val = val;
t->left = NULL;
t->right = NULL;
return t;
}
void freeTree(TREE t) {
if (t != NULL) {
if (t->left != NULL)
freeTree(t->left);
if (t->right != NULL)
freeTree(t->right);
free(t);
}
}
void printNode(TREE t) {
printf("------ NODE ------\n");
printf("t == %p\n", t);
if (t != NULL) {
printf("val = %c\n", t->val);
printf("left : %p\n", t->left);
printf("right : %p\n", t->right);
}
}
void printTree(TREE t) {
if (t != NULL) {
printf("%c\t[%p]\n", t->val, t);
printf("%p\n", t->left);
if (t->left != NULL) {
printf("----------------begin left----------------\n");
printTree(t->left);
printf("----------------end left----------------\n");
}
printf("%p\n", t->right);
if (t->right != NULL) {
printTree(t->right);
}
}
}
/*
* Misc functions
*/
char* concat(char *s1, char *s2)
{
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
//in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}
char* substr(char* s, int start) {
int i = 0;
char* sub = malloc(4*(strlen(s) - start) + 1); // +1 for the zero-terminator
while (s[i+start] != '\0') {
sub[i] = s[i+start];
i++;
}
return sub;
}
char* substr_(char* s, int start, int end) {
int i = 0;
char* sub = malloc(4*(strlen(s) - start) + 1); // +1 for the zero-terminator
while (s[i+start] != '\0' && i < (end-start+1)) {
sub[i] = s[i+start];
i++;
}
return sub;
}
/*
* Regex handling
*/
TREE parseParenthesis(char* regex) {
if (regex[0] == '\0') return NULL;
printf("%s\n",regex);
TREE tree = createNode(regex[0]);
int i = 0;
int start = 1;
int lastParenthesisPos = 0;;
switch (regex[0]) {
case '(' :
while (regex[i] != '\0') {
if (regex[i] == ')')
lastParenthesisPos = i;
i++;
}
tree->left = parseParenthesis(substr_(regex, 1, lastParenthesisPos-1));
start = lastParenthesisPos + 1;
break;
case '|' :
case ')' : // Handled by case ')'
case '*' :
case '+' :
case '?' :
default : break;
}
tree->right = parseParenthesis(substr(regex, start));
return tree;
}
void parseExtras(TREE t, TREE parent) {
if (t == NULL) return;
TREE tmp = NULL;
switch (t->val) {
case '*' :
case '+' :
case '?' :
parseExtras(t->right, t);
tmp = createNode(parent->val);
t->left = tmp;
break;
case '(' :
case ')' :
case '|' :
default :
parseExtras(t->left, t);
parseExtras(t->right, t);
break;
}
}
/*
* Main
*/
int main() {
//char* regex = "a|(b|c*)?d|ef";
char* regex = "ab*dd*";
// Parse ()
TREE t = parseParenthesis(regex);
printf("************************************ OK - Parse parenthesis\n");
// Parse * + ?
parseExtras(t, NULL);
printf("************************************ OK - Parse extras\n");
printTree(t);
printf("************************************ OK - Print tree\n");
freeTree(t);
printf("************************************ OK - Free tree\n");
return 0;
}
You are allocating space only for a pointer, not the actual struct:
TREE t = (TREE) malloc(sizeof(TREE));
After this, you are modifying memory that is beyond the size of TREE (which is a pointer).
As a comment above said, don't use typedef unnecessarily.

The functions && Linked List

I did my best with this program but I could not know where is the error?? I'll explain the program. In this program I should implement a stack of integers as linked list, using a global variable to point to the top of the stack by using these methods:
int push(int i);
push i on the stack, return 1 if successful else return 0.
int pop();
pop number from stack. if stack empty return 0;
I did create new method call int stackEmpty(); and the two method above.
Every time I run my program it's push the numbers into the stack but the pop doesn't work. Here my code:::
#include <stdio.h>
#include <stdlib.h>
typedef struct stack Stack;
struct stack
{
int number;
Stack *next;
};
Stack *top = NULL;
int push(int i);
int count();
int stackEmpty();
int pop();
int main()
{
char op;
int i, x;
printf("Welcome to my stack\n");
printf("p to pop, s to push, c to count, q to quit\n");
while (op != 'q')
{
scanf("%c", &op);
if (op == 'p')
{
x = pop();
if (x == 0)
{
printf("Stack is empty\n");
}
else
{
printf("%d popped\n", pop());
}
}
else if (op == 'c')
{
i = count();
printf("%d numbers on stack\n", i);
}
else if (op == 's')
{
printf("Enter number: ");
scanf("%d", &i);
x = push(i);
if (x == 1 || x == 2)
{
printf("%d puched :: state%d\n", i, x);
}
else
{
printf("faill %d\n", x);
}
}
else if (op == 'q')
{
return 0;
}
}
return 0;
}
int stackEmpty()
{
if (top == NULL)
{
return 1;
}
else
{
return 0;
}
}
int count()
{
int counter = 0;
if (top == NULL)
{
return counter;
}
else
{
while (top != NULL)
{
top = top->next;
counter++;
}
return counter;
}
}
int push(int i)
{
Stack *head;
Stack *next;
Stack *new;
int state;
int m;
head = top;
new = (Stack *) malloc(sizeof(Stack));
if (new == NULL)
{
state = 0;
} new->number = i;
m = stackEmpty();
if (m == 1)
{
head = new;
top = head;
head->next = NULL;
state = 1;
}
else
{
while (head != NULL)
{
if ((next = head->next) == NULL)
next = new;
next->next = NULL;
state = 2;
break;
head = top->next;
next = head->next;
}
top = head;
}
return state;
}
int pop()
{
Stack *head;
int state;
int m;
head = top;
if (head == NULL)
{
state = 0;
}
m = stackEmpty();
if (m == 1)
{
state = 0;
}
else
{
state = head->number;
top = head->next;
free(head);
}
return state;
}
Several problems:
top is your supposed head of the stack I assume. In count you advance top until it is NULL - thus once you called count you have "lost" your stack.
A stack is a LIFO queue (last in first out). Your push would implement a FIFO (first in first out) by appending new elements at the end.
Your push is not actually adding anything to the list. You are just assiging new to next but you are not pointing to next from anywhere in your list.
When using pop you are calling it twice (once for removing the element and once for printing). Therefore you remove two elements whenever you go down that code path. A better implementation would be to write a peek function which returns the top element without removing it and the pop function simply removes it (indicating success with 1 and fail with 0)
A push for a stack goes like this:
Create a new element
Point to your current head as the next element
Make your new element the new head of the stack
No loop needed. It's an O(1) operation.
You are not pushing correctly. You are changing next which is a local variable. you are not changing the "next" value in you list tail.
One problem is that you pop(), then check result, then pop() again while printing. You're popping twice for each time you try to print.
Another error:
while (head != NULL)
{
if ((next = head->next) == NULL)
next = new;
next->next = NULL;
state = 2;
break;
head = top->next;
next = head->next;
}
Should be:
while (head != NULL)
{
if ((next = head->next) == NULL)
{
next = new;
next->next = NULL;
state = 2;
break;
}
head = top->next;
next = head->next;
}
At least, that's what your original indentation seems to indicate.

Resources