用c++设计一个带头结点单链表类,实现单链表的创建、输入、输出、插入、删除、查找、销毁等操作
时间: 2023-12-04 08:36:59 浏览: 118
C语言实现带头结点的链表的创建、查找、插入、删除操作
好的,以下是用C++设计的带头结点单链表类的实现:
```cpp
#include <iostream>
using namespace std;
template <typename T>
class ListNode {
public:
T data;
ListNode<T>* next;
ListNode(T val = 0, ListNode<T>* ptr = nullptr) : data(val), next(ptr) {}
};
template <typename T>
class LinkedList {
private:
ListNode<T>* head;
public:
LinkedList() { head = new ListNode<T>; }
~LinkedList() { clear(); delete head; }
void clear();
bool isEmpty() const { return head->next == nullptr; }
int length() const;
bool insert(int i, const T& x);
bool remove(int i);
int search(const T& x) const;
void input();
void output() const;
};
template <typename T>
void LinkedList<T>::clear() {
ListNode<T>* p = head->next, *q;
head->next = nullptr;
while (p != nullptr) {
q = p->next;
delete p;
p = q;
}
}
template <typename T>
int LinkedList<T>::length() const {
ListNode<T>* p = head->next;
int len = 0;
while (p != nullptr) {
len++;
p = p->next;
}
return len;
}
template <typename T>
bool LinkedList<T>::insert(int i, const T& x) {
if (i < 0) return false;
ListNode<T>* p = head;
int j = -1;
while (p != nullptr && j < i - 1) {
p = p->next;
j++;
}
if (p == nullptr) return false;
ListNode<T>* q = new ListNode<T>(x, p->next);
p->next = q;
return true;
}
template <typename T>
bool LinkedList<T>::remove(int i) {
if (i < 0) return false;
ListNode<T>* p = head;
int j = -1;
while (p != nullptr && j < i - 1) {
p = p->next;
j++;
}
if (p == nullptr || p->next == nullptr) return false;
ListNode<T>* q = p->next;
p->next = q->next;
delete q;
return true;
}
template <typename T>
int LinkedList<T>::search(const T& x) const {
ListNode<T>* p = head->next;
int i = 0;
while (p != nullptr && p->data != x) {
p = p->next;
i++;
}
if (p == nullptr) return -1;
else return i;
}
template <typename T>
void LinkedList<T>::input() {
clear();
int n;
cin >> n;
for (int i = 0; i < n; i++) {
T x;
cin >> x;
insert(i, x);
}
}
template <typename T>
void LinkedList<T>::output() const {
ListNode<T>* p = head->next;
while (p != nullptr) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
```
阅读全文