在這部分代碼:
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