单链表实现

单链表的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();
}















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值