根据你提供的要求,这里给出一个实现带头结点的单链表的示例代码:
#include <iostream>
using namespace std;
template <class ElemType>
struct Node {
ElemType data;
Node<ElemType> *next;
};
template <class ElemType>
class LinkList {
public:
LinkList() {
first = new Node<ElemType>; // 创建头结点
first->next = nullptr;
}
LinkList(ElemType a[], int n) {
first = new Node<ElemType>; // 创建头结点
first->next = nullptr;
for (int i = 0; i < n; i++) {
insert(i + 1, a[i]);
}
}
~LinkList() {
clear();
delete first; // 删除头结点
}
int len() {
int count = 0;
Node<ElemType> *p = first->next;
while (p != nullptr) {
count++;
p = p->next;
}
return count;
}
ElemType getElem(int i) {
if (i <= 0 || i > len()) {
throw "Invalid index!";
}
Node<ElemType> *p = getNode(i);
return p->data;
}
int locate(ElemType x) {
int pos = 1;
Node<ElemType> *p = first->next;
while(p != nullptr && p->data != x){
pos++;
p= p->next ;
}
if (p == nullptr){
return -1; // 表示未找到该元素
} else{
return pos; // 返回找到的位置
}
}
void insert(int i, ElemType x) {
if (i <= 0 || i > len() + 1) {
throw "Invalid index!";
}
Node<ElemType> *p = getNode(i - 1);
Node<ElemType> *newNode = new Node<ElemType>;
newNode->data = x;
newNode->next = p->next;
p->next = newNode;
}
ElemType deleteElem(int i) {
if (i <= 0 || i > len()) {
throw "Invalid index!";
}
Node<ElemType> *p = getNode(i - 1);
Node<ElemType> *q = p->next;
ElemType x = q->data;
p->next = q->next;
delete q;
return x;
}
void dispList() {
Node<ElemType> *p = first->next;
while(p != nullptr){
cout << p -> data << " ";
p= p -> next ;
}
cout << endl;
}
private:
Node<ElemType>* first;
Node<ElemType>* getNode(int i) {
if (i < 0 || i > len()) {
throw "Invalid index!";
}
int count = 0;
Node<ElemType> *p = first;
while(count < i){
count++;
p= p -> next ;
}
return p;
}
void clear(){
while(first -> next != nullptr){
deleteElem(1);
}
}
};
int main() {
int r[10] ={4,2,6,8,12,10,14,16,19,18};
LinkList<int> L(r, 10);
cout << "执行插入操作前数据为:" << endl;
L.dispList(); /*输出所有元素*/
L.insert(6, 11); /*在6号位置插入元素11*/
cout << "执行插入操作后数据为:" << endl;
L.dispList(); /*输出所有元素*/
cout << "值为16的元素位置为:";
cout << L.locate(16) << endl; /*查找元素16,并返回在顺序表中的位置*/
cout << "执行删除第7个元素操作,删除前数据为:" << endl;
L.dispList(); /*输出所有元素*/
L.deleteElem(7); /*删除第7个元素*/
cout << "删除后数据为:" << endl;
L.dispList(); /*输出所有元素*/
return 0;
}
这段代码实现了带头结点的单链表类 LinkList,并进行了验证。你可以根据需要对其进行修改和扩展。
内容由零声教学AI助手提供,问题来源于学员提问




