[英]Copying and then sorting a linked list
I have a linked list of Nodes, each Node is defined as: 我有一个节点的链接列表,每个节点定义为:
struct Node {
char name[14];
int counts[130];
char gender;
Node *nextPtr;
};
I am copying this linked list with the following code: 我使用以下代码复制此链接列表:
// Create a copy of the current list
Node *tempPtr;
while (headPtr != NULL) {
tempPtr = new Node;
tempPtr = headPtr;
// Advance the list
headPtr = headPtr->nextPtr;
} // End while loop
I need to copy the list so that I can sort it, I do not want to sort the original list. 我需要复制列表以便对其进行排序,但我不想对原始列表进行排序。 The sorting will be descending based on a value at a certain position of the counts[] array. 排序将基于counts []数组某个位置的值进行降序。 I am wondering is somebody could tell me, am I copying the list correctly? 我想知道有人可以告诉我,我是否正确复制了清单? And if I can have some insight as to how to go about and sort this list. 而且,如果我对如何处理此列表有一些见解。 I have written this in Java with no problem, I apologize for knowing too little of the c programming language. 我已经用Java毫无问题地写了这个,对于您对c编程语言了解太少,我深表歉意。 Any input will be greatly appreciated. 任何输入将不胜感激。 Thank you. 谢谢。
My apologies, I am to write this in the c++ programming language. 抱歉,我要用c ++编程语言编写此代码。 However, I am not allowed to use C++ classes. 但是,不允许使用C ++类。 I can only use C++ I/O stream, reference parameters, and dynamic memory allocation. 我只能使用C ++ I / O流,参考参数和动态内存分配。
My main goal here is to make a list of pointers to the existing nodes, and then sort it without copying the nodes or disturbing the original list. 我在这里的主要目标是制作一个指向现有节点的指针的列表,然后对其进行排序,而不会复制节点或干扰原始列表。
There's no such thing as new
in C. Are you using a c++ compiler? C语言中没有new
东西。您正在使用c ++编译器吗?
Ignoring that, the problem is you aren't copying anything, and in fact are creating a memory leak: 忽略这一点,问题在于您没有复制任何内容,实际上正在造成内存泄漏:
tempPtr = new Node;
tempPtr = headPtr;
You create a new node on the heap, assigning the pointer to tempPtr
... then reassign tempPtr
to headPtr
. 您在堆上创建一个新节点,将指针分配给tempPtr
...,然后将tempPtr
重新分配给headPtr
。 You just lost that newly allocated Node
(memory leak). 您刚刚丢失了新分配的Node
(内存泄漏)。
To make a copy of the list, you need to iterate through your existing list, copying the data into new nodes that you're adding to a new list. 要复制列表,您需要遍历现有列表,将数据复制到要添加到新列表的新节点中。
Node *oldNode = headPtr;
Node *newHead = malloc(sizeof(struct Node));
Node *tail = newHead;
while(oldNode != NULL)
{
memcpy(tail, oldNode, sizeof(struct Node));
oldNode = oldNode->nextPtr;
if (oldNode != NULL)
{
tail->nextPtr = malloc(sizeof(struct Node));
tail = tail->nextPtr;
}
}
(untested and I've not done C for a while but that should do it) (未经测试,我已经一段时间没有做过C了,但是应该这样做)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.