为什么这个C代码只打印第一个&最后一个节点?

时间:2009-12-02 18:55:41

标签: c linked-list

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

typedef struct 
{
  char *Name;
  int grade;
  int cost;
}Hotel;    /*This is data element in each node*/

typedef struct hinfo
{
  Hotel h;
  struct hinfo *next;
}Hinfo;   /*This is a single node*/

typedef struct
{
  Hinfo *next; /*This is the head pointer of the linked list*/
}HotelHead;

void createHotel(HotelHead *h);
void DisplayHotel(HotelHead h);

int main()
{
  HotelHead *list=(HotelHead *)malloc(sizeof(HotelHead));
  list->next=NULL;
  createHotel(list);
  DisplayHotel(*list);
  return(0);
}

void createHotel(HotelHead *h)  /*This function creates the list of hotels*/
{
  char ans='y';
  while(ans=='y' || ans=='Y')
  {
    char *name=(char *)malloc(20*sizeof(char));
    Hinfo *new=(Hinfo *)malloc(sizeof(Hinfo));
    printf("\nEnter hotel name: ");
    scanf("%[A-Za-z0-9 ]",name);
    printf("\nEnter hotel grade & cost: ");
    scanf("%d %d",&new->h.grade,&new->h.cost);
    new->h.Name=name;
    new->next=NULL;
    if(h->next==NULL){h->next=new;}
    else
    {
      Hinfo *current=h->next;
      while(current->next!=NULL){current->next=current->next->next;}
      current->next=new;
    }
    printf("\nEnter another hotel?(Y/N): ");
    scanf("%s",&ans);
    getchar();          /*dummy getchar to eat unwanted character*/
  }
}

void DisplayHotel(HotelHead h)  /*This function displays all hotels in the list*/
{
  Hinfo *current=h.next;
  printf("\nHotel list:\n");
  while(current!=NULL)
  {
    printf("\n%s %d %d\n",current->h.Name,current->h.grade,current->h.cost);
    current=current->next;
  }
}

3 个答案:

答案 0 :(得分:4)

您希望在行走列表时移动current,而不是更改current->next的值。改变这个:

while (current->next != NULL) {
    current->next = current->next->next;
}

到此:

while (current->next != NULL) {
    current = current->next;
}

也就是说,最好在添加新节点的同时移动current,而不是每次从开始处走链接列表。例如(骨架代码):

Hinfo *current;

while (...) {
    Hinfo *new = malloc(sizeof(Hinfo));

    // initialize new node

    if (current != NULL) {
        current->next = new;
    }

    current = new;

    // prompt to enter more nodes
}

答案 1 :(得分:2)

DisplayHotel功能还可以!问题在于createhotel功能。 当你这样做时:

while( current->next != NULL ){
  current->next = current->next->next;
}

在这里,您实际上是在更改列表,删除元素。 尝试做:

while( current->next != NULL ){
  current = current->next;
}

最好的方法是始终有一个指向头部列表最后一个元素的指针,因此您可以直接添加新元素,而不是总是遍历整个列表! (记得在添加新元素时更新头部)

答案 2 :(得分:0)

这是不正确的:

char * name =(char *)malloc(sizeof(20));

您正在分配(sizeof(int))个字节,而不是20个字节。

无论你做什么,这都会导致问题。