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;
}
本文详细介绍了使用C++实现单链表的数据结构过程,包括插入元素、获取链表长度和打印链表等功能。通过具体代码示例,展示了单链表的基本操作和内存管理。
944

被折叠的 条评论
为什么被折叠?



