新人友好型C++实现单链表;附链表翻转;
程序员文章站
2022-03-04 18:50:16
...
还记得刚接触算法的时候,觉得看视频太慢,在网上找了好几个单链表的C++实现,发现一千个人,一千个C++代码风格。所以自己也写了一个代码,为代码基数+1,相信新人总能在某一款中发现新思路,豁然开朗。
因为代码不多,结构比较简单,函数的声明和实现放一起了,感觉看起来更方便吧。希望能有用!如有纰漏,也欢迎各位大佬批评指正!
话不多说,直接上代码。
#include <string>
#include <iostream>
using namespace std;
class Node
{
public:
int m_data;
Node* m_next;
Node(int data = 0,Node* next = nullptr)
{
m_data = data;
m_next = next;
}
};
class LinkList
{
int size;
Node head;
public:
LinkList()
{
size = 0;
}
~LinkList()
{
this->clear();
}
void append_element(int data)
{
Node* newnode = new Node;
Node* temp = head.m_next; //为遍历链表创建的一个临时变量
if (head.m_next == nullptr)
{
head.m_next = newnode;
newnode->m_data = data;
size++;
}
else
{
while (1)
{
if (temp->m_next == nullptr)
{
newnode->m_data = data;
temp->m_next = newnode;
size++;
break;
}
temp = temp->m_next;
}
}
}
int traval()
{
Node* temp = head.m_next;
if (size == 0)
{
return 0;
}
while (1)
{
cout << temp->m_data << "->";
if (temp->m_next == nullptr) break;
temp = temp->m_next;
}
cout << "nullptr" << endl;
}
void getsize()
{
cout << "The LinkList's size = " << size << endl;
}
void insert(int data,int position)
{
if (position < 0 || position >= size) cout << "Index is out of range." << endl;
else if (position == 0) //头插 计数从0开始,这很程序员
{
Node* newnode = new Node;
Node* temp;
temp = head.m_next;
head.m_next = newnode;
newnode->m_next = temp;
newnode->m_data = data;
size++;
}
else if (position == size - 1) //尾插 为什么不用append?
{
Node* newnode = new Node;
Node* temp = head.m_next;
while (1)
{
if (temp->m_next == nullptr)
{
temp->m_next = newnode;
newnode->m_data = data;
size++;
break;
}
temp = temp->m_next;
}
}
else
{
Node* newnode = new Node;
Node* cur = head.m_next;
Node* temp;
for (size_t i = 0; i < position - 1; i++) cur = cur->m_next;
temp = cur->m_next;
cur->m_next = newnode;
newnode->m_next = temp;
newnode->m_data = data;
size++;
}
}
void reverse()
{
Node* cur = head.m_next;
Node* pre = nullptr, * next;
while (true)
{
next = cur->m_next;
cur->m_next = pre;
pre = cur;
cur = next;
if (cur == nullptr)
break;
}
head.m_next = pre;
}
void clear()
{
Node* cur = head.m_next;
Node* temp;
while (true)
{
temp = cur->m_next;
delete cur;
cur = temp;
if (cur == nullptr)
break;
}
size = 0;
}
};
int main()
{
LinkList test;
test.append_element(5);
test.append_element(10);
test.append_element(15);
test.traval();
test.getsize();
test.insert(20, 0);
test.traval();
test.getsize();
test.insert(30, 3);
test.traval();
test.insert(1, 2);
test.traval();
test.reverse();
test.traval();
test.clear();
test.traval();
}