在这部分代码:
while(temp!=NULL && temp->data!=loc)
{
temp=temp->next;
}
if(temp==NULL)
{
printf("\n%c is not present in list ",loc);
}
else
{
temp1=temp->next;
temp->next=var;
var->previous=temp;
var->next=temp1;
temp1->previous=var;
}
这可能是temp
不为空,但temp->next
是(即,如果temp
是最后一个项目在列表中)。然后你会得到一个分割故障线路temp1->previous = var;
...
编辑因为你仍在努力得到这个工作,我写了一个完整的例子。这使用了一个稍微不同的结构 - 我有一个函数来找出插入的位置,另一个插入。我相信你可以弄清楚你的代码不通过这个代码所做的相同步骤,并且你可以从这里找出它。
我插入了几条printf
语句来确认事情是按照预期工作的 - 在调试过程中这通常是一个好主意。
我希望这有助于!
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *previous;
char data;
struct node *next;
}*head, *last;
struct node * insertBetween(struct node * p1, struct node * p2, char value)
{
struct node* newItem = (struct node *)malloc(sizeof(struct node));
printf("inserting between %p and %p\n", p1, p2);
newItem->data = value;
newItem->next = p2;
newItem->previous = p1;
if (p1 == NULL)
{
printf("have a new head!\n");
head = newItem;
head->next = p2;
if (p2 != NULL) p2->previous = head;
else last = newItem;
}
else
{
p1->next = newItem;
p2->previous = newItem;
}
printf("insertBetween completed\n");
return newItem;
}
int before(char value, char loc)
{
struct node *temp,*var,*temp1, *penultimate=NULL;
if(head==NULL)
{
printf("creating head\n");
head = insertBetween(NULL, NULL, value);
}
else
{
temp=head;
while(temp!=NULL && temp->data!=loc)
{
printf("data is %c\n", temp->data);
temp=temp->next;
}
if(temp==NULL)
{
printf("\n%c is not present in list \n",loc);
}
else
{
// create a new element
insertBetween(temp->previous, temp, value);
}
}
// confirming that "last" is still the last element - should not need this:
// and that the list integrity is intact
temp=head;
while(temp->next!=NULL)
{
printf("element %p has value %c and points to element %p\n", temp, temp->data, temp->next);
temp=temp->next;
}
printf("in the end, temp is %p and last is %p\n", temp, last);
}
int main(void) {
before('z','a');
before('y','z');
before('x','y');
before('X','y');
before('2', 'z');
printf("inserted everything!\n");
return 0;
}
是否为不同的主题创建单独的问题;并发布足够的代码,以便我们可以重现您的错误。当你调用'之前'时,'value'和'loc'的值是多少?什么可以防止多次调用'before'之前巨大的内存泄漏(并且'var'一直指向新的内存)?如何定义'struct node'?如此多的问题... – Floris 2013-05-10 03:23:11
更新,如果需要更多,请让我知道:) – Hamas4 2013-05-10 03:27:30
请参阅:http://sscce.org/ - 修复缩进将有帮助 – xaxxon 2013-05-10 04:17:54