【发布时间】:2016-07-06 00:01:33
【问题描述】:
我正在做一个学校作业,我正在制作一个 int 链表,它应该具有对其进行排序的功能。我很确定我根据输出得到了正确的链接。排序函数应该交换节点,而不是值。我收到分段错误(核心转储)消息,不确定它的含义或原因。我正在寻求有关为什么它不起作用的帮助。我对指针仍然很糟糕,所以我认为这是一个问题。我的排序也是插入排序
typedef struct node {
int data;
struct node *next;
struct node *prev;
} node;
node *pHead = NULL; // head of list
node *pCurr = NULL; // current node
int count = 0;
void create(int data) {
node *pNode = (node*) malloc(sizeof(node));
pNode->data = data;
pNode->next = NULL;
pNode->prev = NULL;
pHead = pCurr = pNode;
count += 1;
}
void add(int data) {
if (pHead == NULL) {
return create(data);
}
node *pNode = (node*) malloc(sizeof(node));
pNode->data = data;
pNode->next = NULL;
pNode->prev = pCurr;
pCurr->next = pNode;
pCurr = pNode;
count += 1;
}
int size() {
return count;
}
void print() {
node *pNode = pHead;
while (pNode != NULL) {
printf("[%d]->", pNode->data);
pNode = pNode->next;
}
printf("\n");
}
void sort(node *current) {
pHead = current;
node *pInsert = pHead;
current = current->next;
int i, j;
for (i = 0; i < size(); i++) {
for (j = i; j > 0; j--) {
if (current->data >= pInsert->data) {
node *pTemp = current;
current = pInsert;
pInsert = pTemp;
}
pInsert = pInsert->prev;
}
current = current->next;
}
print();
}
【问题讨论】:
-
快速浏览一下,我发现您没有 NULL 保护,因此您可以尝试取消引用空指针
-
您实际上并没有交换节点。您只是在更改
current和pInsert指向的内容。 -
在受交换影响的所有节点中更改
next和prev指向的内容。 -
Current= current->next如果您的当前节点是最后一个节点,稍后将导致段错误。在if (current->data >= pInsert->data)处添加一个 NULL 指针保护 -
是的,现在当你处理链表时,尤其是当你有 prev/next 指针时,要移动东西,你需要一个 delete 函数和一个 insert 函数。删除函数基本上采用一个节点,并执行如下操作:
node->prev->next = node->next应该有效地将其从列表中删除。然后你的插入函数看起来像nodeIWantToInsert->next = insertionPoint->next, nodeIWantToInsert->previous = insertionPoint, nodeIWantToInsert->next->previous = nodeIWantToInsert
标签: c