【发布时间】:2016-05-22 06:18:18
【问题描述】:
我正在使用 C 语言进行一个小型学习项目,但在实现将保存数据集的第一个数据值的头节点时遇到了麻烦。我应该采用一个未排序的链表并使用它来实现一个排序的链表。它应该像下面的例子那样分成两个函数。
为堆上的头指针节点分配内存时出现了我的问题。使用 malloc 时,它似乎总是创建一个数据值为 0 的额外头节点(0 不在数据集中,但可能在)。
struct node* create_sorted_list(struct node *head)
{
struct node * curr = head;
struct node * sorted_head = malloc(sizeof(struct node));
while(curr != NULL){
add_item_sorted(sorted_head, curr->data);
curr=curr->next;
}
return sorted_head;
}
struct node* add_item_sorted(struct node *sorted_head, int data)
{
struct node * curr = sorted_head;
struct node * newN;
while(curr->next != NULL){
if(data > curr->next->data){
curr=curr->next;
}
else{
newN = malloc(sizeof(struct node));
newN->data = data;
newN->next = curr->next;
curr->next = newN;
return sorted_head;
}
}
newN = malloc(sizeof(struct node));
curr->next = newN;
newN->data = data;
return sorted_head;
}
int main(int argc, char *argv[])
{
......
struct node * sorted_head = create_sorted_list(head);
//head in this case comes from an unsorted linked list with the
//same data values. Using head linked list to make sorted_head.
}
我的输出是这样的:0 -> 56 -> 35 -> 98 -> end
什么时候应该是:56 -> 35 -> 98 -> 结束
我有理由相信额外的节点是一对多调用 malloc 的结果,但是我找不到正确的解决方案。
感谢任何帮助。多谢你们。
【问题讨论】:
标签: c data-structures linked-list singly-linked-list