コードのこの部分では:
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 ではなく、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;
}