關於連結串列的一些理解
#define NULL 0
struct student
{
long num;
float score;
struct student *next;
};
main()
{
struct student a, b, c, *head, *p;
a.num=99101; a.score=89.5;
b. num=99103;
c.num=99107 ; c.score=85;
head=&a; a.next=&b; b.next=&c; c.next=NULL;p=head;
do
{ printf("%ld %5.1f\n",p->num,p->score);
p=p->next
1.為什麼在結構體內,結構體student 還沒有定義好,而就在其內部使用呢?不是說先定義後使用的嗎?”這時student這個型別可以使用,但是個不完全型別,只能以有限方式使用,不能定義該型別的物件,不完全型別只能用於定義指向該型別的指標及引用.就是說next指向了struct student 型別的物件,但是具體只想誰並不知道。
2.struct student a, b, c, *head, *p 都是struct的具體物件,而next是struct的一個成員變數,next的型別是指向
3.指標物件指向成員時使用->:p->num,p->score,p->next
4.普通物件指向成員時使用,: a.next,a.num,a.score
3.因為next存放的是下一個物件的地址,p->next 是 p 所指向的結構的 next 成員,存放的是下一個物件的地址。p=p->next,就讓p指向了下一個結點的資料。
c++版本簡單鏈表程式
整體思路是:1.定義類成員的型別指標class list *next
2.定義類型別名與指標型別名,使用別名參與運算
3.定義指向連結串列頭的指標,與類成員指標同類型,為delptr
4.定義指向當前節點的指標ptr
5.定義新的節點newnode
6.new分配記憶體,node* delptr=new node,此時delptr指向連結串列頭,併為成員賦值
7.ptr=delptr; //保留連結串列頭指標,以ptr為指向當前節點的指標
8.建立新節點newnode,並分配記憶體,將此時newnode指向該節點,併為成員賦值
9.清空newnode的成員next中的指向 newnode->next=NULL,此時為孤立節點
10.建好頭結點和孤立節點之後把孤立節點連線到連結串列後面ptr->next=newnode
11.ptr=ptr->next; //讓ptr保持在連結串列的最後面,ptr->next裡存放的是下一個物件的地址,賦值給ptr即將指向物件向前移動一位。
12.最後還需釋放空間delete,避免發生記憶體洩漏。
#include <iostream>
using namespace std;
class list
{
public:
int num,score;
char name[10];
class list *next; //next指向了類list,next是一個指標,指向了另一個類例項,這樣可以形成連結串列。
};
typedef class list node; //定義類型別名,將node定義為list的同義詞
typedef node *link; /將link定義為node*的同義詞,link指向node。
int main()
{
link newnode,ptr,delptr ; //宣告三個連結串列結構的指標
cout<<"請輸入 5 位學生的資料:"<<endl;
delptr=new node; //delptr暫當連結串列頭指標https://blog.csdn.net/xxpresent/article/details/53024555
if (!delptr)
{
cout<<"[Error!!記憶體分配失敗!]"<<endl;
exit(1);
}
cout<<"請輸入座號:";
cin>>delptr->num;
cout<<"請輸入姓名:";
cin>>delptr->name;
cout<<"請輸入成績:";
cin>>delptr->score;
ptr=delptr; //保留連結串列頭指標,以ptr為指向當前節點的指標
for (int i=1;i<5;i++)
{
newnode=new node; //建立新節點
if(!newnode)
{
cout<<"[Error!!記憶體分配失敗!"<<endl;
exit(1);
}
cout<<"請輸入座號:";
cin>>newnode->num;
cout<<"請輸入姓名:";
cin>>newnode->name;
cout<<"請輸入成績:";
cin>>newnode->score;
newnode->next=NULL;
ptr->next=newnode; //把新節點加在連結串列後面
ptr=ptr->next; //讓ptr保持在連結串列的最後面
}
cout<<"\n 學 生 成 績"<<endl;
cout<<" 座號\t姓名\t成績\n====================="<<endl;
ptr=delptr; //讓ptr回到連結串列頭
while(ptr!=NULL)
{
cout<<ptr->num<<"\t"<<ptr->name<<"\t"<<ptr->score<<endl;
delptr=ptr;
ptr=ptr->next; //ptr按序往後遍歷整個連結串列
delete delptr; //釋放記憶體空間
}
system("pause");
}