0
該程序應該採取一個用戶輸入的整數,並通過單向鏈接列表將其轉換爲二進制。我認爲它是我的toBin()函數或我的printStack()函數導致的無限循環。無法解決無限循環
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct node_def node;
struct node_def
{
int val;
node *next;
};
node *head;
void push(int val);
void pop(node *head);
int top();
void printStack();
int toBin(int val);
int main()
{
int num = 0;
printf("Enter an integer: ");
scanf("%d", &num);
push(num);
toBin(num);
printStack();
return 0;
}
void push(int val)
{
node *new;
new = malloc(sizeof(node));
if (head == NULL)
{
head = malloc(sizeof(node));
head->next = NULL;
head->val = val;
}
else
{
new->next = head;
new->val = val;
head = new;
}
return;
}
void pop(node *head)
{
node *tmp;
if(head == NULL)
{
printf("Stack is Empty\n");
return;
}
else
{
tmp = head;
head = head->next;
free(tmp);
}
return;
}
int top()
{
return(head->val);
}
void printStack()
{
node *tmp;
tmp = head;
if(head == NULL)
{
return;
}
while(head != NULL)
{
printf("%d ", head->val);
head = head->next;
}
printf("\n");
return;
}
int toBin(int val)
{
pop(head);
int i = 1, remainder, binary;
while(val != 0)
{
remainder = val % 2;
binary = binary + remainder * i;
val = val/2;
i = i * 10;
push(binary);
}
return val;
}
在'printStack()'定義'tmp'但不使用它。相反,你修改全局'head',從此'head'就沒用了。 –
@WeatherVane我也在我的pop()函數中做了這個。改變了兩者之後,無限循環消失了,謝謝! – mychem97
但是,在'pop(node * head)'中可以,因爲你正在修改一個傳值參數,而不是被'printStack()修改的全局變量' – bruceg