我的双链表实现如下,每个节点都有一个由四个值组成的数组
#define EMPTYNODE 0
struct node {
short data[4]; // pay attention
struct node* next;
struct node* prev;
};
typedef struct node nodeQ_t;
typedef enum{
LIST_FALSE = 0,
LIST_TRUE = 1,
} status_t;
nodeQ_t* createNode(short values[4]){
nodeQ_t* node = (nodeQ_t*)malloc(sizeof(node));
for(int i=0; i < 4; i++){
node->data[i] = values[i];
}
node->next = EMPTYNODE;
node->prev = EMPTYNODE;
return node;
}
现在,我正试图以一种方式编写append函数,即为其提供head和createNode函数中创建的节点,以便将其附加到列表中。。。。但它造成了分割错误。。。
status_t appendNode(nodeQ_t* head, nodeQ_t* newNode){
if(head == EMPTYNODE || newNode == EMPTYNODE){
return LIST_FALSE;
};
nodeQ_t* currentNode = head;
while(currentNode != EMPTYNODE){
if(currentNode->next == EMPTYNODE){ //it means that current node is tail
currentNode->next = newNode; //segmenttion fault arises at exactly this line
newNode->prev = currentNode;
}
currentNode = currentNode->next;
}
return LIST_TRUE;
}
请告诉我是什么原因。。。供您参考,我的主要功能是
int main(){
short array[4] = {1,2,3,4};
nodeQ_t* head = createNode(array);
printList(head);
short array2[4] = {5,6,7,8};
nodeQ_t* newNode = createNode(array2);
appendNode(head, newNode);
printList(head);
return 0;
}
如果你需要任何进一步的信息或解释,请告诉我
如注释中所述,一旦到达终点,您需要break
退出循环:
while(currentNode != EMPTYNODE) {
if (currentNode->next == EMPTYNODE) {
currentNode->next = newNode;
newNode->prev = currentNode;
// need a break here
}
currentNode = currentNode->next;
// When at the end of the list the 1st time through,
// currentNode is the newly created node because you have
// currentNode->next = newNode
// then
// currentNode = currentNode->next
// On the next iteration, the new node next ends up getting pointed to itself
// since on that iteration newNode and currentNode are the same.
// and you end up with an infinite loop.
}
另一种选择是在currentNode->next
:上循环
while (currentNode->next) {
currentNode = currentNode->next;
}
currentNode->next = newNode;
newNode->prev = currentNode;
我应该注意,这是有效的,因为您之前已经确保currentNode
不是NULL
。
此外,您在这里的分配是错误的:
nodeQ_t* node = (nodeQ_t*)malloc(sizeof(node));
因为node
是指针,而sizeof(node)
是指针的大小,而不是struct node
的大小。应该是
nodeQ_t* node = (nodeQ_t*)malloc(sizeof(*node));
你最终会陷入无尽的循环:
while(currentNode != EMPTYNODE){
if(currentNode->next == EMPTYNODE){ //it means that current node is tail
currentNode->next = newNode; //segmenttion fault arises at exactly this line
newNode->prev = currentNode;
}
CCD_ 8将总是不同于CCD_ 9。添加新元素后添加中断或返回:
while(currentNode != EMPTYNODE){
if(currentNode->next == EMPTYNODE){ //it means that current node is tail
currentNode->next = newNode; //segmenttion fault arises at exactly this line
newNode->prev = currentNode;
return LIST_TRUE;
}