0

C で二重にリンクされたリストの実装をコーディングしました。その中で、値を挿入した後、値が重複しています。つまり、私が指定した最後の値がすべてのリスト項目で複製されます。

私のコードは次のとおりです

header.h

#include<stdio.h>
#include<stdlib.h>
typedef struct doubly_list
{
 int id;
 char *name;
 struct doubly_list *next;
 struct doubly_list *prev;
}node;
void insertfirst(node **,int ,char *);
void insertlast(node **,int ,char *);

doublely_list_insert.c

#include"header.h"
    void insertfirst(node **head,int id,char *name)
    {
     node *tmp=(node *)malloc(sizeof(node));
     if(NULL == tmp)
     {
      printf("\nMemory allocation failed\n");
      exit(1);
     }
     tmp->id=id;
     tmp->name=name;
     tmp->prev=NULL;
     if(*head== NULL)
     {
      tmp->next=NULL;
      *head=tmp;
     }
     else
     {
      tmp->next=*head;
      (*head)->prev=tmp;
      *head=tmp;
     }
    }

    void insertlast(node **head,int id,char *name)
    {
     if(*head==NULL)
     {
      insertfirst(head,id,name);
      return;
     }
     node *last=*head;
     node *tmp=(node *)malloc(sizeof(node));
     if(NULL == tmp)
     {
      printf("\nMemory allocation failed\n");
      exit(1);
     }
     tmp->id=id;
     tmp->name=name;
     tmp->next=NULL;
     while(last->next!=NULL)
     {
      last=last->next;
     }
     last->next=tmp;
     tmp->prev=last;
    }

doublely_list_traverse.c

#include"header.h"
void traverse(node *head)
{
 node *tmp=head;
 if(head==NULL)
 {
  printf("\nList is empty\n");
  exit(1);
 }
 while(tmp!=NULL)
 {
  printf("%d --> %s\n",tmp->id,tmp->name);
  tmp=tmp->next;
 }
}

そして、ここにメインファイルが来ます、

main.c

#include"header.h"
int main()
{
 int choice;
 int id;
 char name[15];
 node *root=NULL;
 system("clear");
 while(1)
 {
  printf("\n1.Insert First\n");
  printf("\n2.Insert Last\n");
  printf("\n3.Traverse\n");
  printf("\n4.Exit\n");
  printf("\nEnter your choice : ");
  scanf("%d",&choice);
  switch(choice)
  {
   case 1:
        printf("\nEnter the employee id : ");
        scanf("%d",&id);
        printf("\nEnter the employee name : ");
        scanf("%s",name);
        insertfirst(&root,id,name);
        break;
   case 2:
        printf("\nEnter the employee id : ");
        scanf("%d",&id);
        printf("\nEnter the employee name : ");
        scanf("%s",name);
        insertlast(&root,id,name);
        break;

   case 3:
        traverse(root);
        break;
   case 4:
        return 0;
        break;
   default:
        printf("\nPlease enter valid choices\n");
  }
 }
}

実行中に、最初または最後に1つのデータのみを挿入すると、適切に入力を取得します。

しかし、2 つ目を挿入すると、問題が発生します。私の場合、id 値は同じままです。ただし、2 番目の入力の名前の値が 1 番目の値に重複しています。

なぜこれが起こっているのですか?引数を渡すのに何か問題がありますか?

4

1 に答える 1

2

新しいノードを作成するときは、ポインターを名前にコピーするだけでノード名を設定します。ポインタではなく文字列をコピーする必要があります。関数はこれstrdupに最適です:

tmp->name=strdup(name);

freeノードを解放するときは、名前を覚えておいてください。

編集

insertfirst初めて呼び出したときに何が起こるかというと、最初のノードのフィールドが の配列をname指しているということです。2 番目のノードの名前を取得すると、配列の内容が新しい名前で更新され、最初のノードのポインターがその配列を指しているため、名前が重複しているように見えます。namemainmain

于 2011-12-01T11:27:07.607 に答える