【发布时间】:2014-12-06 07:51:38
【问题描述】:
正如标题所暗示的那样。删除链表中的第一个节点就像一个魅力。是那些其他的节点!好的,这是我的代码。我认为我正在正确删除,但我没有正确链接。
结构体和类型定义如下所示:
typedef struct List *ListP;
typedef struct Entry *EntryP;
typedef char *ListItemP;
struct List
{
int sizeL;
struct Entry *head;
};
struct Entry
{
ListItemP content;
struct Entry *next;
int sizeL;
};
removeItemList 函数在 main.c 中的工作方式是传递一个列表指针 (ListP thisList) 和一个字符串 (ListItemP thisItem)。传递参数后,该函数会搜索与列表中的节点相同的字符串(通过 strcmp()),并在找到时将其删除。 NewEntry 初始化了 Entry 结构,并有一个将字符传递给 newEntry->content 的输入。无论如何,这是功能:
void removeItemList(ListP thisList, ListItemP thisItem)
{
EntryP temp = newEntry(0x00);
EntryP temp2 = newEntry(0x00);
temp->next = thisList->head;
temp2->next = thisList->head;
if (strcmp(temp->next->content, thisItem) == 0)
{
thisList->head = temp->next->next;
}
else {
while(temp->next != 0x00)
{
if(strcmp(temp->next->content,thisItem) == 0) {
break;
}
temp->next = temp->next->next;
temp->sizeL++;
}
if (temp->next == 0x00) {
}
else {
int i = 0;
for(i = 0; i < temp->sizeL - 1 ; i++)
{
temp2->next = temp2->next->next;
printf("%s \n", temp2->content);
}
temp2->next = temp->next->next;
free(temp2->next);
}
}
thisList->sizeL--;
}
我认为被删除节点之前的节点最终被指向 null。不过,我无法弄清楚如何解决这个问题。我想这就是我在这里的原因!任何事情都将不胜感激,非常感谢!
编辑:更新代码,加上显示列表代码
更新了 removeItemList()
void removeItemList(ListP thisList, ListItemP thisItem)
{
EntryP current = newEntry(0x00);
EntryP prev = newEntry(0x00);
prev = 0x00;
current = thisList->head;
if (strcmp(current->content, thisItem) == 0)
{
thisList->head = current->next->next;
}
else {
while (current->next != 0x00)
{
prev = current;
current = current->next;
if (strcmp(current->content, thisItem) == 0)
{
prev->next = current->next;
free(current);
}
}
}
}
显示列表():
void displayList(ListP thisList)
{
EntryP temp = newEntry(0x00);
temp->next = thisList->head;
while(temp->next != 0x00)
{
printf("%s \n", temp->next->content);
temp->next = temp->next->next;
}
free(temp);
}
如果我只使用 printf() 语句,我可以正常访问所有内容,并且该节点似乎已删除。但是,如果我尝试使用 displayList() 打印它们,则在打印节点后会在删除节点之前出现段错误。所以看起来好像我没有正确链接节点。
【问题讨论】:
标签: c pointers linked-list nodes