gpt4 book ai didi

c - 将节点添加到链表中

转载 作者:行者123 更新时间:2023-11-30 16:23:39 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来获取链表的头、链表的尾部、添加节点 (n) 的位置、数字和价格。

链表中的每个节点都包含一个数字,该数字也是该节点在链表中的位置。这里的东西不起作用,由于某种原因,它一直将新节点放置在链表的第一个位置。谢谢您的帮助。这是一张如何打印的照片:

image

void AddNewItem(PItem *head, PItem *tail, int n, int a, float b){
PItem temp = *head, curr = *head;
temp->num = a;
temp->price = b;
temp = (PItem*)malloc(sizeof(PItem));

while (n < temp->num) {
temp = temp->next;
curr = curr->next;
}
temp->next = curr->next;
curr->next = temp;
}

这是结构:

typedef struct Item
{
int num;
float price;
struct Item* next;
}*PItem;

最佳答案

以下建议代码:

  1. 消除未使用的参数
  2. 干净地编译
  3. 执行所需的操作
  4. 正确检查错误

现在,建议的代码:

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

// format struct definition for readability
// and eliminate undesireable 'typedef' of a pointer
struct Item
{
int num;
float price;
struct Item* next;
};


// use meaningful names for paramters and
// allow for this might be first entry into linked list
void AddNewItem(struct Item **head, int num, float price)
{
struct Item *curr = *head;
struct Item *prev = *head;

struct Item *newNode = malloc(sizeof(struct Item));
if( !newNode )
{
perror( "malloc failed" );
exit( EXIT_FAILURE );
}

// implied else, malloc successful

// initialize fields of new node
newNode->num = num;
newNode->price = price;
newNode->next = NULL;

// check if first node added to linked list
if( !*curr )
{ // then first addition to linked list
*curr = newNode;
}

else
{
// check for end of linked list and
// check for found desired position in linked list
while ( curr->next )
{
if( curr->num >= newNode->num )
{
break;
}

// implied else

prev = curr;
curr = curr->next;
}

// insert the new item into the linked list
newNode->next = curr;
prev->next = newNode;
}
}

关于c - 将节点添加到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53925334/

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