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


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

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

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

下面給出它們的簡單實現,關於線性表更為詳盡的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");
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM