帶頭結點的單鏈表類C++手動實現

最近在複習數據結構,看到單鏈表這部分,現在用的教材大部分都是嚴蔚敏的C語言版吧,參考了一些書籍,手動編寫了C++下單鏈表類的實現,環境是Visual Studio 2010,函數是對照着教材聲明挑了個寫的。代碼如下:

/*帶頭結點的單鏈表類C++手動實現
作者:許多*/

#include <iostream>
using namespace std;
class MyList; //提前聲明
class LNode{ //結點類
friend MyList;
private:
int data;
LNode *next;
};
class MyList{ //鏈表類
public:
void InitList(int n); //頭插法初始化帶頭結點的表,長度爲n,不算頭結點
void DestroyList(); //摧毀表
void ClearList(); //清空表
bool ListEmpty(); //判空
int ListLength(); //取表長
int GetElem(int i); //取第i個結點的值
int LocateElem(int e); //找出值爲e的元素是第幾個元素
bool ListInsert(int i, int e); //第i個位置插入元素e
bool ListDelete(int i); //刪除第i個元素
void PrintList(); //輸出鏈表
private:
LNode *head; //頭指針
};
void MyList::InitList(int n)
{
int x;
head = new LNode;
head->next = NULL;
for(int i=n;i>0;--i)
{
cin>>x;
LNode *p = new LNode;
p->data = x;
p->next = head->next;
head->next = p;
}
}
void MyList::DestroyList()
{
delete head;
cout<<"表摧毀了!"<<endl;
}
void MyList::ClearList()
{
head->next = NULL;
cout<<"清空完畢!"<<endl;
}
bool MyList::ListEmpty()
{
if(head->next == NULL) return true;
else return false;
}
int MyList::ListLength()
{
LNode *p=head;
int j=0;
while(p->next)
{
p=p->next;
j++;
}
return j;
}
int MyList::GetElem(int i)
{
int j=1;
LNode *p=head->next; //第一個結點
if(i<1) return NULL;
while(p&&j<i)
{
p=p->next;
j++;
}
return p->data;
}
int MyList::LocateElem(int e)
{
int i=0;
LNode *p=head->next;
while(p!=NULL&&p->data!=e)
{
p=p->next;
i++;
}
if(p==NULL) return 0;
else return i+1;
}
bool MyList::ListInsert(int i, int e)
{
LNode *p, *s;
int j=1;
p=head;
while(p&&j<i) {p=p->next;j++;}
if(p==NULL) return false;
if((s = new LNode)==NULL) return false;
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
bool MyList::ListDelete(int i)
{
LNode *p,*q;
int j=1;
p=head;
while(p&&j<i) { p=p->next;j++;}
if(p==NULL) return false;
q=p->next;
p->next=q->next;
delete q;
return true;
}
void MyList::PrintList()
{
if(ListEmpty()) { cout<<"表是空的!"<<endl; }
else
{
cout<<"表中元素爲:";
LNode *p = head->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
}
 

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