(C++版)連結串列(一)——實現單向連結串列建立、插入、刪除等相關操作
阿新 • • 發佈:2019-01-30
前段時間用C語言實現了連結串列的相關操作,但是發現當時挺清楚的,過了一段時間又忘的差不多了,所以現在打算用C++再實現一遍,由於初次用C++實現,存在錯誤的地方還望大家指標。下面就直接上程式碼:
#include <iostream>
#include <stdlib.h>
using namespace std;
//結點類
class Node {
public:
int data;
Node *pNext;
};
//單向連結串列類
class LinkList {
public:
LinkList() {
//頭結點不參與計數
head = new Node;
head->data = 0;
head->pNext = NULL;
}
~LinkList() { delete head; }
void CreateLinkList(int n); //建立連結串列
void InsertNode(int position, int d); //在指定位置插入結點
void TraverseLinkList(); //遍歷連結串列
bool IsEmpty(); //判斷連結串列是否為空
int GetLength(); //連結串列長度
void DeleteNode(int position); //刪除指定位置結點
void DeleteLinkList(); //刪除整個連結串列
private:
Node *head;
};
void LinkList::CreateLinkList(int n) {
if (n < 0) {
cout << "輸入結點個數錯誤!" << endl;
exit(EXIT_FAILURE);
}
else {
Node *pnew, *ptemp;
ptemp = head;
int i = n;
while (n-- > 0) {
pnew = new Node;
cout << "輸入第" << i - n << "個結點值:";
cin >> pnew->data;
pnew->pNext = NULL;
ptemp->pNext = pnew;
ptemp = pnew;
}
}
}
//postion從1開始計數,到連結串列長度加1結束,頭結點後的結點稱為第一個結點
void LinkList::InsertNode(int position, int d) {
if (position < 0 || position > GetLength() + 1) {
cout << "輸入位置錯誤!" << endl;
exit(EXIT_FAILURE);
}
else {
Node *pnew, *ptemp;
ptemp = head;
pnew = new Node;
pnew->data = d;
pnew->pNext = NULL;
while (position-- > 1)
ptemp = ptemp->pNext;
pnew->pNext = ptemp->pNext;
ptemp->pNext = pnew;
}
}
void LinkList::TraverseLinkList() {
Node *p = head->pNext;
while (p != NULL) {
cout << p->data << " ";
p = p->pNext;
}
cout << endl;
}
bool LinkList::IsEmpty() {
if (head->pNext == NULL)
return true;
else
return false;
}
int LinkList::GetLength() {
Node *p = head->pNext;
int n = 0;
while (p != NULL) {
n++;
p = p->pNext;
}
return n;
}
//position只能從1開始到連結串列長度結束
void LinkList::DeleteNode(int position) {
if (position < 0 || position > GetLength()) {
cout << "輸入位置錯誤!" << endl;
exit(EXIT_FAILURE);
}
else {
Node *ptemp = head, *pdelete;
while (position-- > 1)
ptemp = ptemp->pNext;
pdelete = ptemp->pNext;
ptemp->pNext = pdelete->pNext;
delete pdelete;
pdelete = NULL;
}
}
void LinkList::DeleteLinkList() {
Node *pdelete = head->pNext, *ptemp;
while(pdelete != NULL) {
ptemp = pdelete->pNext;
head->pNext = ptemp;
delete pdelete;
pdelete = ptemp;
}
}
//測試函式
int main() {
LinkList l;
int position = 0, value = 0, n = 0;
bool flag = false;
cout << "請輸入需要建立單向連結串列的結點個數:";
cin >> n;
l.CreateLinkList(n);
cout << "列印連結串列值如下:";
l.TraverseLinkList();
cout << "請輸入插入結點的位置和值:";
cin >> position >> value;
l.InsertNode(position, value);
cout << "列印連結串列值如下:";
l.TraverseLinkList();
cout << "請輸入要刪除結點的位置:";
cin >> position;
l.DeleteNode(position);
cout << "列印連結串列值如下:";
l.TraverseLinkList();
l.DeleteLinkList();
flag = l.IsEmpty();
if (flag)
cout << "刪除連結串列成功!" << endl;
else
cout << "刪除連結串列失敗!" << endl;
return 0;
}
上面是單向連結串列的實現,和C的實現其實是差不多的,就是換了一種描述方式。要注意的地方還是和C語言實現是一樣的,測試結果如下: