title: 单链表的c++实现
date: 2018-03-21 15:33:14
categories: leetcode与算法
tags:
- 链表
- 单链表
这个一篇单链表的c++实现小练习
#include<iostream>
using namespace std;
/**
* 单链表的c++实现
*/
struct node
{
int val;
struct node* next;
node(int v): val(v), next(NULL) {}
};
class List
{
private:
node* head;
public:
List()
{
head = NULL;
}
~List();
void insert(int val);
int getLen();
void print();
};
List::~List()
{
node* p;
while(head!=NULL)
{
p = head;
head = head->next;
delete(p);
}
}
void List::insert(int val) {
node* node_p = new node(val);
node* p = head;
if(p == NULL)
{
head = node_p;
return;
}
while(p->next != NULL)
{
p = p->next;
}
p->next = node_p;
}
int List::getLen() {
node* p = head;
int res = 0;
while(p != NULL)
{
res += 1;
p = p->next;
}
return res;
}
void List::print() {
node* p = head;
while(p != NULL)
{
cout<<p->val<<endl;
p = p->next;
}
}
int main()
{
List l;
cout<<l.getLen()<<endl;
l.insert(2);
cout<<l.getLen()<<endl;
l.insert(3);
cout<<l.getLen()<<endl;
l.print();
return 0;
}