复制链表然后排序
我有一个节点链表,每个节点定义为:
struct Node {
char name[14];
int counts[130];
char gender;
Node *nextPtr;
};
我正在使用以下代码复制此链表:
// 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
我需要复制该列表以便可以对其进行排序,我不想对原始列表进行排序。排序将根据 counts[] 数组中特定位置的值进行降序排序。我想知道有人可以告诉我,我是否正确复制了列表?如果我能对如何处理和排序这个列表有一些见解。我用 Java 写的,没有任何问题,我很抱歉对 C 编程语言了解太少。任何意见将不胜感激。谢谢。
抱歉,我要用 C++ 编程语言编写此内容。但是,我不被允许使用 C++ 类。我只能使用C++ I/O流、引用参数和动态内存分配。
我的主要目标是创建一个指向现有节点的指针列表,然后对其进行排序,而不会复制节点或干扰原始列表。
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. 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. Any input will be greatly appreciated. Thank you.
My apologies, I am to write this in the c++ programming language. However, I am not allowed to use C++ classes. I can only use C++ I/O stream, reference parameters, and dynamic memory allocation.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C 中没有 new 之类的东西。您使用的是 c++ 编译器吗?
忽略这一点,问题是您没有复制任何内容,实际上正在造成内存泄漏:
您在堆上创建一个新节点,将指针分配给
tempPtr
...然后重新分配tempPtr
到headPtr
。您刚刚丢失了新分配的Node
(内存泄漏)。要创建列表的副本,您需要迭代现有列表,将数据复制到要添加到新列表的新节点中。
(未经测试,我已经有一段时间没有做过 C 但应该可以了)
There's no such thing as
new
in C. Are you using a c++ compiler?Ignoring that, the problem is you aren't copying anything, and in fact are creating a memory leak:
You create a new node on the heap, assigning the pointer to
tempPtr
... then reassigntempPtr
toheadPtr
. You just lost that newly allocatedNode
(memory leak).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.
(untested and I've not done C for a while but that should do it)