【发布时间】:2016-03-26 05:02:14
【问题描述】:
我正在尝试实现一个链表,并从 addToFront 函数开始。 这里我只是将数字 5 添加到列表的前面。我知道如果列表为空,则列表指针应该为 Null,但是,情况似乎并非如此。
编辑文件: 我已经编辑了文件(感谢 taskinoor 的回答),现在提供了
的输出0 5
代替
5
我有头文件:
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
typedef struct List {
struct list * next;
int value;
int size;
}list;
void addToFront(int num, list **l);
void printList(list * l);
int getSize(list * l);
void initialize(list * l);
void freeList(list *l);
一个c文件“main.c”
#include "Header.h"
int main() {
list l;
initialize(&l);
addToFront(5, &l);
printList(&l);
_getch();
freeList(&l);
return 0;
}
void printList(list * l) {
list *current = l;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
}
void freeList(list *l) {
list *current = l;
while (current != NULL) {
list *tmp = current;
current = current->next;
free(tmp);
}
}
还有一个接口c文件(不完整)
#include "Header.h"
int getSize(list * l) {
return l->size;
}
void initialize(list * l) {
l->next = NULL;
l->value = 0;
l->size = 0;
}
// need to pass **l to update it
void addToFront(int num, list **l) {
// allocate memory for new node
list *tmp = (list *)malloc(sizeof(list));
tmp->value = num;
// new node should point to whatever head is currently pointing
// even if head is NULL at beginning
tmp->next = *l;
// finally l needs to point to new node
// thus new node becomes the first node
*l = tmp;
}
但是,当调用 addToFront 函数时,永远不会执行 if 语句。哪个没有意义,如果列表为空,列表指针不应该为空吗?
接下来我尝试在Initialize function 中手动设置l == NULL,但这也没有任何作用。此外,我的打印函数无限循环,我认为这是 malloc 的问题。任何帮助将不胜感激。
【问题讨论】:
-
如果
if (l == NULL)那么你不能像l->value= ...一样取消引用它!! -
嗯,但是我将如何设置要插入的新节点的值(恰好是列表中的第一个节点)。尽管如此,更大的问题是为什么 if 语句没有执行。
-
...和“手动
set l == NULL”也不起作用,因为==是比较运算符,而不是赋值运算符。也许你想检查l->next == NULL? -
但是'l->next'不是列表中的第二个节点,而不是第一个节点吗?
-
if语句可能已执行,但l不是NULL,因为您已在 main 中为其分配了内存。l->next虽然是 NULL
标签: c++ c algorithm data-structures linked-list