有头指针和尾指针的单链表的基本操作代码
时间: 2023-11-23 14:52:09 浏览: 48
有头指针和尾指针的单链表基本操作代码如下:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
Node* tail;
public:
LinkedList() {
head = new Node();
tail = head;
}
void insert(int val) {
Node* newNode = new Node();
newNode->data = val;
tail->next = newNode;
tail = newNode;
}
void remove(int val) {
Node* cur = head->next;
Node* pre = head;
while (cur != nullptr) {
if (cur->data == val) {
pre->next = cur->next;
if (cur == tail) {
tail = pre;
}
delete cur;
return;
}
pre = cur;
cur = cur->next;
}
}
void print() {
Node* cur = head->next;
while (cur != nullptr) {
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.print();
list.remove(2);
list.print();
return 0;
}
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)