C 结构体示例

2018-07-04 11:37 更新

学习C - C结构体示例

双向链接列表

双向列表可以通过任一方向列出。

除了指向下一个结构体的指针之外,我们还需要在每个结构体中添加一个额外的指针来存储先前结构体的地址。


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

typedef struct Dog Dog;       // Define Dog as a type name 
  
struct Dog                      // Structure type definition 
{ 
  int age; 
  int height; 
  char name[20]; 
  char father[20]; 
  char mother[20]; 
  Dog *next;                    // Pointer to next structure 
  Dog *previous;                // Pointer to previous structure 
}; 
int main(void) { 
  Dog *first = NULL;            // Pointer to first Dog 
  Dog *current = NULL;          // Pointer to current Dog 
  Dog *last = NULL;             // Pointer to previous Dog 
  
  char test = "\0";               // Test value for ending input 
  
  for( ; ; ) { 
    printf_s("Do you want to enter details of a%s Dog (Y or N)? ", first != NULL?"nother" : ""); 
    scanf_s(" %c", &test, sizeof(test)); 
    if(tolower(test) == "n") 
      break; 
  
    // Allocate memory for each new Dog structure 
    current = (Dog*) malloc(sizeof(Dog)); 
    if(first == NULL){ 
      first = current;            // Set pointer to first Dog 
     current->previous = NULL; 
    } else { 
      last->next = current;       // Set next address for previous Dog 
      current->previous = last;   // Previous address for current Dog 
    } 
    printf_s("Enter the name of the Dog: "); 
    scanf_s("%s", current->name, sizeof(current->name)); 

    printf_s("How old is %s? ", current->name); 
    scanf_s("%d", &current->age); 

    printf_s("How high is %s ( in hands )? ", current -> name ); 
    scanf_s("%d", &current->height); 

    printf_s("Who is %s"s father? ", current->name); 
    scanf_s("%s", current->father,sizeof(current->father)); 

    printf_s("Who is %s"s mother? ", current->name); 
    scanf_s("%s", current->mother, sizeof(current->mother)); 

    current->next = NULL;         // In case it"s the last... 
    last = current;               // ...save its address 
  } 

  // Now tell them what we know. 
  printf_s("\n"); 
  while(current != NULL)          // Output Dog data in reverse order 
  { 
    printf_s("%s is %d years old, %d hands high,", 
               current->name, current->age, current->height); 
    printf_s(" and has %s and %s as parents.\n", current->father, 
                                            current->mother); 
    last = current;               // Save pointer to enable memory to be freed 
    current = current->previous;  // current points to previous in list 
    free(last);                   // Free memory for the Dog we output 
    last = NULL; 
  } 
  first = NULL; 
  return 0; 
} 

上面的代码生成以下结果。



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号