单链表的C艹实现,留做LeetCode使用
#include <iostream>
using namespace std;
struct Node
{
int val;
Node *next;
};
class NodeList
{
private:
Node *head;
Node *tail;
public:
NodeList();
~NodeList(){}
int GetElem(int i);
void InsertNodeh(int a);
void InsertNodet(int a);
bool DeleteNode(int i);
void CreatList(int n);
bool DeleteList();
bool IsEmpty();
int GetNum();
void print();
void removeElements
};
NodeList::NodeList()
{
head = new Node;
tail = head;
tail->next = head;
}
void NodeList::InsertNodeh(int a)
{
//从头部插入一个数值为a的结点
Node *temp = new Node;
temp->val = a;
temp->next = head->next;
head ->next = temp;
if (tail == head)
{
tail = temp;
tail->next = NULL;
}
}
void NodeList::InsertNodet(int a)
{
//从尾部插入一个数值为a的结点
Node *temp = new Node;
temp->val = a;
tail ->next = temp;
tail = temp;
tail->next = NULL;
}
bool NodeList::IsEmpty()
{
return tail == head;
}
bool NodeList::DeleteNode(int i)
{
//删除第i个结点
if (i <= 0)
return false;
else
{
int count = 0;
Node *pre = head;
Node *cur = head->next;
while (cur && count != i)
{
count++;
pre = cur;
cur = cur->next;
}
if (count == i)
{
pre->next = cur->next;
delete cur;
return true;
}
else
return false;
}
}
void NodeList::CreatList(int n)
{
while (n)
{
Node *temp = new Node;
tail->next = temp;
tail = temp;
tail->next = NULL;
n--;
}
}
bool NodeList::DeleteList()
{
if (IsEmpty())
return false;
else
{
Node *temp;
while(head->next)
{
temp = head->next;
head->next = temp->next;
delete temp;
}
tail = head;
return true;
}
}
int NodeList::GetNum()
{
Node *temp = head->next;
int count = 0;
while(temp)
{
count++;
temp = temp->next;
}
return count;
}
void NodeList::print()
{
Node *temp = head->next;
while(temp)
{
cout<<temp->val<<" ";
temp = temp->next;
}
cout<<endl;
}
void main()
{
NodeList list;
list.InsertNodet(1);
list.InsertNodet(2);
list.InsertNodet(6);
list.InsertNodet(3);
list.InsertNodet(5);
list.InsertNodet(6);
list.print();
}