【发布时间】:2014-09-03 01:10:29
【问题描述】:
因此,对于我的 C 类课程,我们被告知要创建一个联系人数组(电话号码和姓名),其节点包含列表中下一个联系人的地址。
我是指针的新手,我了解它们的概念,但它们令人困惑。我将评论我的思考过程以及我认为我在做什么。我们提供了很多这样的代码。我只实现了构成 addLast 函数的联系人结构和单词灾难。
typedef struct Contact
{
int *Next;
char *Name;
char *Tel;
} Contact;
Contact *start=NULL; //This start variable dictates the first node in the list.
void builtList(Contact*);
void addLast(Contact*);
void printList();
int main()
{
Contact contacts[7]=
{
{NULL,"Dennis","0203/123456"},
{NULL,"Chantal","0177/3123345"},
{NULL,"Robert","0163/9295986"},
{NULL,"Bjoern","040 - 123232345"},
{NULL,"Andreas","+49 178 11903123"},
{NULL,"Jenny","+41 119 34544345"},
{NULL,"Zeuss","0162-123-4531698"},
};
builtList(contacts);
printList();
return 0;
}
void builtList(Contact contacts[]) //This function was written for us.
//I would prefer to modify this as little as possible.
{
Contact *ptr=NULL;
int i;
for(i=0; i<=6; i++)
{
ptr=&contacts[i];
addLast(ptr);
}
}
void addLast(Contact *AddressOfCurrent)
{
/* This is the function I am struggling with. We are told this function is to
"add a Contact element to the end of the singly linked list". From what I understand,
It obtains the ADDRESS of the next node and places it into the current node. Thereby
establishing a link between two elements in the list. My friend did this without
importing the contacts[] array and just using a '*temp' array. This confuses me
greatly. How do I establish links between elements if I don't have the elements
with me? */
if (start == NULL)
{
start = AddressOfCurrent; //I can figure out how to establish the start.
} else
{
?????????
}
}
澄清一下,这是我的任务;
您的任务是实现一个使用单链接的联系人列表 列表。 在计算机科学中,链表(或更清楚地说,“单链表” list") 是一种数据结构,由一系列节点组成,每个节点 其中包含对中下一个节点的引用(即链接) 顺序。
实现以下结构/变量
创建一个名为 Contact 的结构体,其中包含以下变量 Contact *next(指向列表中下一个元素的指针) char *name (用于存储联系人姓名) char tel(用于存储联系人姓名) 联系人电话号码)创建一个名为的全局联系人变量 “start”指向单链表的起始元素。 实现以下功能(原型见链接源 代码):
addLast(Contact*):在singly的末尾添加一个Contact元素 链表(一些其他不相关的函数)
对于所有列出的操作,您必须分别编写一个新的 C 函数。
【问题讨论】:
-
你可以把单链表想象成一个栈。我还敦促您在尝试编写任何代码之前先在纸上执行此操作。
-
没有人回答你的问题是因为它很难理解。您的列表节点存储在数组中的事实表明您应该使用数组索引来模拟指针。如果您可以编辑问题以说明作业的确切措辞,这可能有助于人们理解。
-
@ooga 好吧,我在下面附加了实际任务并删除了一些不必要的 cmets,更改了一些代码以使其更清晰。你是对的,我们应该使用数组索引来模拟指针。然而,当所有东西都不在同一个函数中时,这被证明是令人困惑的。
-
实际上,这听起来不像您应该使用数组索引。看起来你应该使用真正的指针。但奇怪的是数据已经存在于数组中。我完全无法理解你的任务。