使用C語言描述靜態鏈表和動態鏈表

原文  http://www.cnblogs.com/choon/p/3915706.html

靜態鏈表和動態鏈表是線性錶鏈式存儲結構的兩種不同的表示方式。

靜態鏈表的初始長度一般是固定的,在做插入和刪除操作時不需要移動元素,僅需修改指針,故仍具有鏈式存儲結構的主要優點。

動態鏈表是相對於靜態鏈表而言的,一般地,在描述線性表的鏈式存儲結構時如果沒有特別說明即默認描述的是動態鏈表。

下面給出它們的簡單實現,關於線性表更爲詳盡的C語言的實現,可以參考http://www.cnblogs.com/choon/p/3876606.html

靜態鏈表

#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#include <stdio.h>
#include <stdlib.h>
/*所有結點都是在程序中定義的,不是臨時開闢的,也不能用完後釋放,這種鏈表稱爲“靜態鏈表”。*/
struct Student
{
  int num;
  float score;
  struct Student *next;
};
int main()
{
  struct Student stu1, stu2, stu3, *head, *p;
  stu1.num = 1001; stu1.score = 80; //對結點stu1的num和score成員賦值
  stu2.num = 1002; stu2.score = 85; //對結點stu2的num和score成員賦值
  stu3.num = 1003; stu3.score = 90; //對結點stu3的num和score成員賦值

  head = &stu1;      //頭指針指向第1個結點stu1
  stu1.next = &stu2; //將結點stu2的地址賦值給stu1結點的next成員
  stu2.next = &stu3; //將結點stu3的地址賦值給stu2結點的next成員
  stu3.next = NULL;  //stu3是最後一個結點,其next成員不存放任何結點的地址,置爲NULL
  p = head;          //使p指針也指向第1個結點

  //遍歷靜態鏈表
  do{
    printf("%d,%f\n", p->num, p->score); //輸出p所指向結點的數據
    p = p->next;                         //然後讓p指向下一個結點
  } while (p != NULL);                     //直到p的next成員爲NULL,即完成遍歷

  system("pause");
}

動態鏈表

#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#include <stdio.h>
#include <stdlib.h>
/*所謂動態鏈表,是指在程序執行過程中從無到有地建立起一個鏈表,即一個一個地開闢結點和輸入各結點數據,並建立起前後相鏈的關係。*/
struct Student
{
  int No;//學號
  struct Student *next;
};
int main()
{
  struct Student *p1, *p2, *head;
  int n = 0; //結點個數
  head = NULL;
  p1 = (struct Student *)malloc(sizeof(struct Student));
  printf("請輸入1個學號\n");
  scanf("%d", &p1->No);
  p2 = p1; //開始時,p1和p2均指向第1個結點
  while (p1->No != 0)
  {
    n++;
    if (n == 1)
    {
      head = p1;
    }
    else
    {
      p2->next = p1;
    }
    p2 = p1;//p2是最後一個結點
    printf("請輸入學號,輸入0終止:\n");
    p1 = (struct Student *)malloc(sizeof(struct Student));
    scanf("%d", &p1->No);
  };
  p2->next = NULL;//輸入完畢後,p2->next爲NULL

  //遍歷動態鏈表
  struct Student *p;
  p = head;
  while (p != NULL)
  {
    printf("%d,", p->No);
    p = p -> next;
  }
  printf("\n");

  system("pause");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章