- 什么是鏈表
鏈表是一種常見的重要的數據結構。它是動態進行儲存分配的一種結構
- 和數組的區別
數組存放數據時,必須事先定義數組長度,如果不知道具體長度,只能定義一個足夠大的長度
鏈表則沒有這種缺點,他能根據需要開辟內存單元
- 結點
每個結點包括兩個數據,用戶實際的數據+下一個結點的地址
- 最后一個元素
該元素不在指向其他元素,它的地址部分放NULL;
- 靜態鏈表
這個例子比較簡單,所有結點都是在程序中定義的,不是臨時開辟的,也不能用完后釋放,這種鏈表成為靜態連表
#include<stdio.h> struct MyStruct { int id; float score; MyStruct *next; }; int main() { struct MyStruct a, b, c, *head, *p; a.id = 111; a.score = 1.1; b.id = 222; b.score = 2.2; c.id = 333; c.score = 3.3; head = &a; a.next = &b; b.next = &c; c.next = NULL; p = head; while (p!=NULL) { printf("%d,%lf\n", p->id, p->score); p = p->next; } }
- 建立動態連表
所謂建立動態鏈表是指在程序運行當中從未到有地建立一個鏈表,即是一個個地開辟結點和輸入各結點的數據,並建立起前后相連的關系
#include<iostream>//最簡單的鏈表
using namespace std;
struct stu
{
int id;
double score;
stu *next;
};
int n=0;
stu * creat()//創建鏈表,輸入數據返回頭結點
{
stu *p1,*p2,*head;
p1=p2=new stu();//很重要這塊,考試之前一定打在打兩遍 ,一個個建立結點,開辟空間
head=NULL;
cin>>p1->id>>p1->score;
while(p1->id!=0)//五角星
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=new stu();
cin>>p1->id>>p1->score;
}
p2->next=NULL;
return head;
}
void print(stu *head)//遍歷鏈表
{
stu *p;
p=head;
while(p!=NULL)//是while不是if
{
cout<<p->id<<p->score<<endl;
p=p->next;
}
}
int main()
{
stu *p;
p=creat();
print(p);
}