链表中的节点未正确删除?

时间:2019-01-03 00:20:52

标签: c linked-list singly-linked-list

我已经发布了MCVE代码,可以将其复制并在任何IDE中运行以检查结果。

链接列表中的输入如下:

Kevlar Epoxy 43.75 18.90 1.48 0.34 0.148 3.93
Kevlar Polycarbonate 43.40 14.00 1.39 0.34 0.110 2.75
Kevlar ABS 43.42 13.94 1.35 0.35 0.112 2.74

我正在寻找的结果是:

Kevlar Epoxy 43.75 18.90 1.48 0.34 0.148 3.93
Kevlar ABS 43.42 13.94 1.35 0.35 0.112 2.74

我得到的结果是:

Kevlar Epoxy 43.75 18.90 1.48 0.34 0.148 3.93
Some random symbols 43.40 14.00 1.39 0.34 0.110 2.75
Kevlar ABS 43.42 13.94 1.35 0.35 0.112 2.74

在此问题中,我试图删除中间节点,因此我不考虑第一个和最后一个节点。请有人让我知道为什么会这样吗?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct lamina
{
  char lamina_fiber[30];
  char lamina_matrix[30];
  float E1,E2,p,v12,v21,G12;
  struct lamina *nextnode;
};

 int main()
{
  struct lamina *head,*data;
  head=(struct lamina *)calloc(1,sizeof(struct lamina));
  data=head;

 strcpy(data->lamina_fiber,"Kevlar");
 strcpy(data->lamina_matrix,"Epoxy");
 data->E1= 43.75;
 data->E2= 18.90;
 data->p= 1.48;
 data->v12= 0.34;
 data->v21= 0.148;
 data->G12= 3.93;

 data->nextnode=(struct lamina *)calloc(1,sizeof(struct lamina));
 data=data->nextnode;

 strcpy(data->lamina_fiber,"Kevlar");
 strcpy(data->lamina_matrix,"Polycarbonate");
 data->E1= 43.40;
 data->E2= 14.00;
 data->p= 1.39;
 data->v12= 0.34;
 data->v21= 0.110;
 data->G12= 2.75;

 data->nextnode=(struct lamina *)calloc(1,sizeof(struct lamina));
 data=data->nextnode;     

strcpy(data->lamina_fiber,"Kevlar");
strcpy(data->lamina_matrix,"ABS");
data->E1= 43.42;
data->E2= 13.94;
data->p= 1.35;
data->v12= 0.35;
data->v21= 0.112;
data->G12= 2.74;

data=head;

struct lamina *temp,*anothertemp;
temp=(struct lamina *)calloc(1,sizeof(struct lamina));
anothertemp=(struct lamina *)calloc(1,sizeof(struct lamina));

temp=data;
size_t i=0;

while(i<1)
{    
 temp=temp->nextnode; 
 i++;
}

if(i==1)
{
 anothertemp=temp->nextnode;
 anothertemp=temp;
 free(temp); 
}

  for(int i=0;i<3;i++)
   {
      printf("%s %s %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
      data->lamina_fiber,data->lamina_matrix,data->E1,data->E2,data->p, 
      data->v12,data->v21,data->G12);
      data=data->nextnode;
   }

}

1 个答案:

答案 0 :(得分:2)

strcpy(data->lamina_fiber,"Kevlar");
strcpy(data->lamina_fiber,"Polycarbonate");

应该是

strcpy(data->lamina_fiber,"Kevlar");
strcpy(data->lamina_matrix,"Polycarbonate");

否则,您将打印未初始化的内存(这是“某些随机符号”的原因)

此外,如果要删除第二个节点,则必须修改第一个节点(头):

head->next = head->next->next;

要释放已删除的节点,请首先将head->next保存到一个临时变量中,最后释放它。