gpt4 book ai didi

c - 在C中的链表的开头插入条目

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

晚上好。在过去的一两个月里,我一直忙于使用 Stephen Kochan 所著的 The C Programming Language Third Edition 一书自学 C。我已经走到这一步了,但是,现在,对于我的生活,我无法弄清楚,在不更改 InsertEntry 函数的情况下,如何在下面的链表的开头插入一个条目。谁能帮我解决这个问题或指出正确的方向?谢谢!

//Insert a an entry at the beginning of a linked list
//Cannot change InsertEntry

struct Entry
{
int Value;
struct Entry *Next;
};

int main()
{
void InsertEntry(struct Entry *InsertPosition, struct Entry *EToInsert);

struct Entry N1, N2, N3, N4, Insert, *Start, *First;

N1.Value = 10;
N2.Value = 20;
N3.Value = 40;
N4.Value = 50;
Insert.Value = 60;
N1.Next = &N2;
N2.Next = &N3;
N3.Next = &N4;
N4.Next = (struct Entry *) 0;
Start->Next = &N1;

First = &N1;
InsertEntry(Start, &Insert);


while(First != 0)
{
printf("%i\n", First->Value);
First = First->Next;
}

return 0;
}

void InsertEntry(struct Entry *InsertPosition, struct Entry *EToInsert)
{
EToInsert->Next = InsertPosition->Next;
InsertPosition->Next = EToInsert;
}

最佳答案

您的 InsertEntry 函数旨在插入元素InsertPosition,因此您不能使用它在第一个位置插入元素。

为了在第一个位置插入一个元素,你需要做这样的事情:

struct Entry newFirst;
newFirst.Value = 75;
newFirst.Next = oldFirst;

关于c - 在C中的链表的开头插入条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33687133/

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