跟着《大话数据结构》实现单链表。创建链表的时候借鉴了大佬的代码,可以说是直接复制粘贴,
#include<iostream>
#include<string>
using namespace std;
typedef int DataType;
class Node
{
public:
DataType data;
Node* next;
};
class List
{
public:
Node* head;
int lenth = 0;
List();
void showList();
int createList(int lenth);
int insertListNode(int position,DataType data);
int deleteListNode(int position);
int deleteList();
~List();
};
List::List()
{
head = new Node;
this->lenth = 0;
head->data = this->lenth;
head->next = nullptr;
}
void List::showList()
{
cout << "一共有" << this->lenth << "个结点" << endl;
Node* temp = this->head;
for (int i = 0; i < this->lenth; i++)
{
cout << "第" << i + 1 << "个结点的值为:" << temp->next->data << endl;
temp = temp->next;
}
}
int List::createList(int lenth)
{
if (lenth < 0)
{
cout << "错误" << endl;
return -1;
}
Node* nodeNew = nullptr;
Node* nodeTemp = nullptr;
this->lenth = lenth;
nodeTemp = this->head;
for (int i = 0; i < lenth; i++)
{
nodeNew = new Node;
nodeNew->next = nullptr;
cout << "共" << lenth << "个结点" << "请输入第" << i + 1 << "个结点的值:" << endl;
cin >> nodeNew->data;
nodeTemp->next = nodeNew;
nodeTemp = nodeNew;
}
cout << "创建成功!!" << endl;
return 0;
}
int List::insertListNode(int position, DataType data)
{
if (position > this->lenth || position < 0)
{
cout << "错误" << endl;
return -1;
}
Node* newNode = new Node;
newNode->data = data;
Node* tempNode = this->head;
for (int i = 0; i < position-1; i++)
{
tempNode = tempNode->next;
}
newNode->next = tempNode->next;
tempNode->next = newNode;
this->lenth++;
return 0;
}
int List::deleteListNode(int position)
{
if (position > this->lenth || position < 0)
{
cout << "错误" << endl;
return -1;
}
Node* tempNode = this->head;
for (int i = 0; i < position-1; i++)
{
tempNode = tempNode->next;
}
tempNode->next = tempNode->next->next;
this->lenth--;
return 0;
}
int List::deleteList()
{
if (this->lenth == 0)
{
cout << "已经是空链表了" << endl;
return -1;
}
Node* tempNode1, * tempNode2;
tempNode1 = this->head->next;
while (tempNode1)
{
tempNode2 = tempNode1->next;
delete tempNode1;
tempNode1 = tempNode2;
this->lenth--;
}
this->head = nullptr;
cout << "删除成功" << endl;
return 0;
}
List::~List()
{
delete head;
}
int main()
{
List L1;
List* pL1 = &L1;
int newPosition, newData,deletePosition;
if (pL1->createList(5) != -1)
{
pL1->showList();
}
cout << "请输入插入位置:" << endl;
cin >> newPosition;
cout << "请输入插入数据:" << endl;
cin >> newData;
if (pL1->insertListNode(newPosition, newData) != -1)
{
pL1->showList();
}
cout << "请输入删除的位置:" << endl;
cin >> deletePosition;
if (pL1->deleteListNode(deletePosition) != -1)
{
pL1->showList();
}
if (pL1->deleteList() != -1)
{
cout << pL1->lenth << endl;
}
system("pause");
return 0;
}