gpt4 book ai didi

c - 带有不需要的零的链表

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:32 25 4
gpt4 key购买 nike

我环顾四周,不确定它是否已发布,但我正在尝试在 C 中创建两个链表。当它们应该为“空”时,它们为零。我不确定这些零是从哪里来的,这让我很困惑。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
int price;
int bookNumber;

struct node * next;

};


void addNode(struct node* pHead, int pPrice, int pBookNumber);
void displayList(struct node* pHead);
void removeNode(struct node* pHead, int pBookNumber);

int main()
{

struct node* head1;
head1 = (struct node*)malloc(sizeof(struct node));
head1 -> next = NULL;

addNode(head1, 10, 1234);
addNode(head1, 35, 9876);
displayList(head1);
printf("\n");
struct node* head2;
head2 = (struct node*)malloc(sizeof(struct node));
head2 -> next = NULL;
// addNode(head2,13, 8888);
displayList(head2);

}

void addNode(struct node* pHead, int pPrice, int pBookNumber)
{

struct node* newNode;
struct node* ptr;

newNode = (struct node*)malloc(sizeof(struct node));

newNode -> price = pPrice;
newNode -> bookNumber = pBookNumber;

newNode -> next = NULL;

ptr = pHead;

if(pHead -> next == NULL)
{
pHead -> next = newNode;
newNode -> next = NULL;
}
else
{
while((ptr -> next != NULL))
{
ptr = ptr -> next;
}

ptr -> next = newNode;
newNode -> next = NULL;

}

}

void removeNode(struct node* pHead,int pBookNumber)
{

struct node *current, *prev;
current = pHead;
/*searching list for the desired data*/
while((current -> bookNumber != pBookNumber))
{

prev = current;

current = current -> next;

}

/*fixing links between nodes*/
prev -> next = current -> next;

/*freeing memory*/
free(current);

/*removing from end of list*/
if((current -> next = NULL))
{

prev -> next = NULL;

/*freeing memory*/
free(current);

}

}

void displayList(struct node* pHead)
{
while(pHead != NULL)
{
printf("$%d, book# %d -> ", pHead -> price, pHead -> bookNumber);
pHead = pHead -> next;
}
printf("NULL");

}

我在第一个列表中添加了两个条目,但没有在第二个列表中添加任何内容...这是输出:

$0, book# 0 -> $10, book# 1234 -> $35, book# 9876 -> NULL
$0, book# 0 -> NULL
Process returned 0 (0x0) execution time : 0.001 s
Press ENTER to continue.

最佳答案

第一个值得注意的问题是您似乎有一个虚拟节点
在列表的开头

struct node* head1;
head1 = (struct node*)malloc(sizeof(struct node));
head1 -> next = NULL;

但是你从 head 开始打印而不是从 head->next
即包括虚拟节点。

关于c - 带有不需要的零的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28710087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com