鏈表是一種動態數據結構,他的特點是用一組任意的存儲單元(可以是連續的,也可以是不連續的)存放數據元素。
鏈表中每一個元素成為“結點”,每一個結點都是由數據域和指針域組成的,每個結點中的指針域指向下一個結點。Head是“頭指針”,表示鏈表的開始,用來指向第一個結點,而最後一個指針的指針域為NULL(空地址),表示鏈表的結束。
可以看出鏈表結構必須利用指針才能實現,即一個結點中必須包含一個指針變量,用來存放下一個結點的地址。
結點中只有一個next指針的鏈表稱為單鏈表,這是最簡單的鏈表結構。
首先定義一個結構體,用於表示鏈表的結點。
struct node{
int data;
node *next;
};
然後建立一個單鏈表的類。
node* list::Create()
{
node *p,*s;
int x=0,cycle=1;
while (cin>>x)
{
s = new node;
s->data = x;
if (NULL == head)
{
head = s;
}
else
{
p->next = s;
}
p = s;
}
p->next=NULL;
if(NULL!=head)
cout<<"創建成功!"<<endl;
else
cout<<"沒有數據輸入!"<<endl;
return head;
}
用以輸出元素
void list::Output()
{
cout<<"\n==========輸出剛才的數據=============\n"<<endl;
node *p = head;
while(p != NULL){
cout<<p->data<<endl;
p=p->next;
}
}
計算該鏈表的長度
int list::Length()
{
int cnt = 0;
node *p = head;
while(p != NULL){
p=p->next;
++cnt;
}
return cnt;
}
刪除某個元素時,如果是head結點時,
void list::Delete(const int aDate)
{
node *p = head,*s;
while (aDate!=p->data&&p->next!=NULL)
{
s=p;// 直到找出相等的結點跳出循環 s存儲前一個結點,p存儲當前結點
p=p->next;
}
if (aDate == p->data)
{
if (p == head)
{
head = p->next;
}
else
{
s->next = p->next;
}
delete p;
}
else
{
cout<<"沒有找到這個數據!"<<endl;
}
}
未完待續。。。。