#include <iostream>
using namespace std;
typedef int T;
class List{
struct Node{
T data;
Node* next;
Node(const T& t=T()):data(t)
{
next = NULL;
}
};
Node* head;
public:
List():head(NULL)
{
}
void clear()
{
while(head != NULL)
{
Node* q = head->next;
delete head;
head = q;
}
}
~List()
{
clear();
}
void insert_front(const T& t)
{
Node* p = new Node(t);
p->next= head;
head = p;
}
void insert_back(const T& t)
{
Node* p = new Node(t);
if (head==NULL)
head = p;
else
{
get_pointer(size()-1)->next = p;
}
}
void travel()
{
Node* p=head;
while(p != NULL)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
int size()
{
int cnt = 0;
Node* p = head;
while(p != NULL)
{
cnt++;
p = p->next;
}
return cnt;
}
T get_head()
{
if (head == NULL)
{
throw "no head";
}
return head->data;
}
T get_tail()
{
if (head == NULL)
throw "no tail";
Node* p = head;
while(p->next != NULL)
{
p = p->next;
}
return p->data;
}
bool empty()
{
return head == NULL;
}
int find(const T& t)
{
int pos = 0;
Node* p = head;
while(p != NULL)
{
if (p->data== t)
return pos;
p = p->next;
pos++;
}
return -1;
}
bool update(const T& o, const T& n)
{
int pos = find(o);
if (pos == -1)
return false;
Node* p = get_pointer(pos);
p->data = n;
return true;
}
private:
Node* get_pointer(int pos)
{
Node* p = head;
for (int i=0; i<pos; i++)
p = p->next;
return p;
}
public:
bool erase(const T& t)
{
int pos = find(t);
if (pos == -1)
return false;
if (pos ==0)
{
Node* q = head->next;
delete head;
head = q;
}
else
{
Node* pre = get_pointer(pos-1);
Node *cur = pre->next;
pre->next= cur->next;
delete cur;
}
}
};
int main()
{
List obj;
obj.insert_front(1);
obj.insert_front(2);
obj.insert_front(3);
obj.insert_front(4);
obj.insert_front(5);
obj.insert_back(88);
cout << "size:" << obj.size() << endl;
obj.travel();
cout << "find 3:" << obj.find(3) << endl;
cout << "find 3:" << obj.find(8) << endl;
obj.update(4, 100);
obj.travel();
obj.erase(3);
obj.erase(5);
obj.erase(1);
obj.travel();
return 0;
}
链表
最新推荐文章于 2020-09-19 23:09:52 发布