在选择此选项并键入我想要在前面添加的字符后,我遇到了段错误。这只是函数仅供引用。
结构:
struct node
{
struct node *previous;
char data;
struct node *next;
}*head, *last;
功能:
int before(int value, int loc)
{
struct node *temp,*var,*temp1;
var=(struct node *)malloc(sizeof(struct node));
var->data=value;
if(head==NULL)
{
head=var;
head->previous=NULL;
head->next=NULL;
}
else
{
temp=head;
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;
}
}
last=head;
while(last->next!=NULL)
{
last=last->next;
}
}
我以为 NULL 会起作用,但事实并非如此,我只需要一些说明来自己尝试一下。
仍然需要一些帮助...
最佳答案
在这部分代码中:
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;
}
关于c - 在双向链表中搜索值并输入之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16474624/