单链表
链表是由结点链接而成,每个结点包含指针域和数据域,其中数据域存储数据元素信息,指针域存储直接后继位置。
我们将链表种第一个结点的存储位置叫做头指针,为了更加方便地对链表进行操作,将会在第一个结点前增加一个结点,称为头结点。
1.定义结点类
struct ListNode
{
int val;
ListNode *next;
ListNode(int x=0xFFFF) :val(x), next(nullptr) {}
};
2.定义链表类
class LinkedList
{
public:
LinkedList();
~LinkedList();
void CreateHead(int n);
void CreateTail(int n);
bool isEmpty() const;
int Find(const int e) const;
int GetItem(int i) const;
void Insert(int i, const int e);
void DeleteEle(const int e);
void DeleteLoc(const int i);
void Display() const;
void Clear();
private:
ListNode *head;
};
CreateHead 方法:使用头插法建立拥有n个元素的单链表;
CreateTail 方法:使用头插法建立拥有n个元素的单链表;
isEmpty 方法:判断链表是否为空;
Find 方法:查找元素并返回该元素在链表中的位置;
GetItem 方法:返回链表中第i个位置的元素值;
Insert 方法:在链表第i个位置插入元素;
DeleteEle 方法:删除链表中第一次出现的值为e的元素;
DeleteLoc 方法:删除链表中位置为i的元素;
Display 方法:按照一定格式打印链表;
clear 方法:整表删除。
3.方法实现
LinkedList::LinkedList()
{
head = new ListNode();
}
LinkedList::~LinkedList()
{
ListNode *p = head;
ListNode *tmp = p->next;
while (tmp)
{
p->next = tmp->next;
delete tmp;
tmp = p->next;
}
delete head;
}
void LinkedList::CreateHead(int n)
{
ListNode *p = head;
for (int i = 0; i < n; i++)
{
ListNode *node = new ListNode(i + 1);
node->next = p->next;
p->next = node;
}
}
void LinkedList::CreateTail(int n)
{
ListNode *p = head;
for (int i = 0; i < n; i++)
{
ListNode *node = new ListNode(i + 1);
node->next = p->next;
p->next = node;
p = node;
}
}
bool LinkedList::isEmpty() const
{
return head->next == nullptr;
}
int LinkedList::Find(const int e) const
{
ListNode *p = head->next;
int j = 0;
while (p && p->val != e)
{
p = p->next;
j++;
}
if (!p)
{
return -1;
}
return j;
}
int LinkedList::GetItem(int i) const
{
ListNode *p = head;
int j = 0;
while (p->next && j < i)
{
p = p->next;
j++;
}
if (j > i || !p->next)
{
return -1;
}
return j;
}
void LinkedList::Insert(int i, const int e)
{
ListNode *p = head;
int j = 0;
while (p && j < i)
{
p = p->next;
j++;
}
if (i > j || !p)
{
return;
}
ListNode *s = new ListNode(e);
s->next = p->next;
p->next = s;
}
void LinkedList::DeleteEle(const int e)
{
ListNode *p = head->next;
ListNode *tmp = head;
while (p->next && p->val != e)
{
p = p->next;
tmp = tmp->next;
}
tmp->next = p->next;
delete p;
}
void LinkedList::DeleteLoc(const int i)
{
ListNode *p = head;
int j = 0;
while (p->next && j < i)
{
p = p->next;
j++;
}
if (j > i && !p->next)
{
return;
}
ListNode *tmp = p->next;
p->next = tmp->next;
delete tmp;
}
void LinkedList::Display() const
{
ListNode *p = head;
while (p->next)
{
std::cout << p->val << "->";
p = p->next;
}
std::cout << p->val << std::endl;
}
void LinkedList::Clear()
{
ListNode *p = head;
ListNode *tmp = p->next;
while (tmp)
{
p->next = tmp->next;
delete tmp;
tmp = p->next;
}
}