因此,对于我在C中的课程,我们被告知要创建一个联系人(电话号码和姓名)数组,其中的节点包含列表中下一个联系人的地址。
我是指针的新手,我得到了它们的概念,但它们令人困惑。我将评论我的思考过程以及我认为我在做什么。我们提供了很多这样的代码。我只实现了构成addLast函数的Contact结构和单词灾难。
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的结构,其中包含以下变量 联系* next(指向列表中下一个元素的指针)char * name (用于存储联系人姓名)char tel(用于存储 联系电话号码)创建一个名为的全局联系变量 “start”指向单链表的起始元素。 实现以下功能(原型见链接源 代码):
addLast(Contact *):将Contact元素添加到单个结尾处 链表(一些其他不相关的功能)
对于所有列出的操作,您必须分别编写一个新的C函数。
答案 0 :(得分:1)
我在帖子中看到的唯一真正的问题就是这个:
我的朋友没有这样做 导入contacts []数组并使用&#39; * temp&#39;阵列。这让我很困惑 很大。如果我没有元素,如何在元素之间建立链接 和我在一起?
由于我们手边没有您的朋友代码,因此难以评估,所以让我们忘记这一点。如果不向addUser()
函数添加参数,您需要一个已声明的全局:
Contact *start=NULL;
所以到处都可以访问。你在addContact()
:
if (!start) {
但是如果start不是NULL,那么你需要通过Next
指针将列表移到最后,这意味着addContact()
函数的另一个必要性:
AddressOfCurrent->Next = NULL;
这意味着每个添加的节点都有一个NULL下一个指针。当另一个节点添加到该节点时,您需要将前一个节点Next
设置为非空:
???->Next = AddressOfCurrent;
???
这是您通过步行找到的当前列表末尾的节点。它是Next == NULL
;)