在这部分代码中:
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
不是 NULL,而是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;
}