我有这个作业,要求我使用动态分配创建堆栈并在其中添加一些不同的功能。现在,通常我会将头指针用作全局变量并使事情变得更容易,但是作业要求我将头指针作为函数的参数,因此我在main中将其设置为局部变量。这是代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node * next;
} node;
void push(int val, node *head) {
node* temp = (node*) malloc(sizeof(node));
node* current = head;
temp->val = val;
if (head == NULL) {
head = temp;
temp->next = NULL;
}
else {
while (current->next != NULL) {
current = current->next;
}
current->next = temp;
temp->next = NULL;
}
}
void print(node *head) {
node* current = head;
if (current->next != NULL) {
while (current->next != NULL) {
printf("%d", current->val);
current = current->next;
}
}
else {
printf("%d", current->val);
}
}
int main() {
node * head = NULL;
int n;
scanf("%d", &n);
push(n, head);
print(head);
push(n, head);
print(head);
push(n, head);
print(head);
}
我在第一个print(head)函数说时遇到了段错误print(head = 0x0)
,这使我相信head在main中返回时不会更新。printf()
在执行第一个push函数后,我使用了for头,对了,头返回0
。问题是:如何在函数中返回更新的头部?
您可以像这样声明您的函数
void push(int val, node **head)
然后传递您的头部参考并对其进行修改
或者
node *push(int val, node *head)
并返回新的头。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句