【发布时间】:2015-01-11 20:00:19
【问题描述】:
我有这个结构
typedef struct node
{
struct node *prev;
void *data;
struct node *next;
}NODE;
typedef struct head
{
unsigned int length;
struct node *first;
struct node *last;
}HEAD;
STATUS addNode(HEAD *head, NODE *newNode, int loc)
{
int i;
STATUS ret = SUCCESS;
NODE *curPtr;
if(head && newNode && loc && (loc <= (head->length)+1))
{
if(loc == 1)
{
newNode->prev = NULL;
newNode->next = head->first;
if(head->first)
head->first = newNode;
}
else
{
curPtr = head->first;
for(i=1; i<(loc-1); i++){
curPtr = curPtr->next;
}
newNode->prev = curPtr;
newNode->next = curPtr->next;
if(curPtr->next){
curPtr->next->prev = newNode;
}
curPtr->next = newNode;
}
head->length++;
}
else
ret = FAILURE;
return ret;
}
STATUS removeNode(HEAD *head,NODE *nodeToRemove)
{
STATUS ret = SUCCESS;
NODE *curPtr;
if(head && head->first)
{
curPtr = nodeToRemove->prev;
curPtr->next = nodeToRemove->next;
if(!(curPtr->next)){
curPtr->next = head->first;
}
head->length--;
}
else
ret = FAILURE;
return ret;
}
我知道我没有在从列表中删除时调用 free(node),这个调用是在其他地方进行的
我的问题是,有时在添加节点中的 newNode->next = curPtr->next; 行上它属于分段错误
你能告诉我这可能发生的原因吗?
【问题讨论】:
-
如果
loc == 1,旧的第一节点prev指针指向什么?如果列表为空,为什么不添加节点呢? -
至于你的分段错误,如果你想最后添加新节点怎么办? IE。当
curPtr是NULL? -
最后,如果您提供的
loc大于列表中的节点数会怎样? -
第一个问题 - 应该指向尾部,第二个问题将其添加到尾部,第三个问题在列表中圈几圈,直到你消耗掉这个位置
标签: c doubly-linked-list