我尝试从该行添加书籍并将其存储在链接列表中。但是,当我尝试这样做时,它会继续从文件中读取。
我在语句if (current == NULL)
之前添加了一个print语句,它返回一个空链表。
读完文件后,我可以得到正确的结果,但一旦弹出if循环,当前节点就会再次变空。
以下是代码:
typedef struct _Book
{
int ISBN;
char Title[20];
char Author[20];
char Description[40];
int CopiesAtCSU;
struct _Book *next;
} Book;
int add(Book **listHead,int ISBN,char *Title,char *Author, int CopiesAtCsu, char *description, int sortIndx){
current = listHead;
prev = null;
newNode = null;
newNode = malloc(sizeof(Book));
newNode->ISBN = ISBN;
//newNode->Title = Title;
strcpy(newNode->Title, Title);
//newNode->Author = Author;
strcpy(newNode->Author, Author);
newNode->CopiesAtCSU = CopiesAtCsu;
//newNode->Description = description;
strcpy(newNode->Description, description);
newNode->next = NULL;
if (*listHead == NULL){
current = newNode;
printf("\n check current in the loop: \n");
displayBookList(current);
listHead = current;
printf("\n ");
}
}
display是一种方法,只需打印链表中的所有项目。
答案 0 :(得分:1)
我认为当您分配到列表头时,您错过了取消引用。
In [45]: %timeit uniques = np.sort(pd.unique(df.values.ravel()))
1 loops, best of 3: 933 ms per loop
In [46]: %timeit dfc = df.apply(lambda x: x.astype('category', categories=uniques))
1 loops, best of 3: 1.35 s per loop
但是,在您的问题中,您在if语句后面说,当前显示为空。这与上面的错误无关。你能展示一下if (*listHead == NULL){
current = newNode;
printf("\n check current in the loop: \n");
displayBookList(current);
*listHead = current; // <------- ERROR: This needs to be dereferenced. In your code you do listhead=current without the dereference.
printf("\n ");
}
方法吗?我非常确定您的问题在于解除引用和间接级别:即使在第一行,您也不应该displayBookList()
而不是current = *listhead
?
答案 1 :(得分:0)
您的代码有点不完整。目前尚不清楚是否要插入列表的前面或末尾。
要在前面插入,newNode->next
必须设置为*listHead
。
要在最后插入,newNode->next
必须设置为NULL
。您必须找到指向现有列表中最后一个节点的指针,因此您需要for
循环。
我提供了两种方式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _Book {
int ISBN;
char Title[20];
char Author[20];
char Description[40];
int CopiesAtCSU;
struct _Book *next;
} Book;
void
add_to_front(Book **listHead,int ISBN,char *Title,char *Author,int CopiesAtCsu,
char *description, int sortIndx)
{
Book *newNode;
newNode = malloc(sizeof(Book));
newNode->ISBN = ISBN;
strcpy(newNode->Title, Title);
strcpy(newNode->Author, Author);
newNode->CopiesAtCSU = CopiesAtCsu;
strcpy(newNode->Description, description);
newNode->next = *listHead;
*listHead = newNode;
}
void
add_to_back(Book **listHead,int ISBN,char *Title,char *Author,int CopiesAtCsu,
char *description, int sortIndx)
{
Book *newNode;
Book *cur;
Book *prev;
newNode = malloc(sizeof(Book));
newNode->ISBN = ISBN;
strcpy(newNode->Title, Title);
strcpy(newNode->Author, Author);
newNode->CopiesAtCSU = CopiesAtCsu;
strcpy(newNode->Description, description);
prev = NULL;
for (cur = *listHead; cur != NULL; cur = cur->next)
prev = cur;
newNode->next = NULL;
if (prev != NULL)
prev->next = newNode;
else
*listHead = newNode;
}