实现带头结点的单链表的建立、求长度,取元素、修改元素、插入、删除等单链表的基本操作。
时间: 2023-05-22 13:06:28 浏览: 80
ChitGPT: 以下是实现带头结点的单链表的基本操作的完整代码。
```
#include<iostream>
using namespace std;
struct Node {
int data;
Node *next;
};
class LinkedList {
private:
Node *head;
public:
LinkedList() {
head = new Node; //创建头结点
head->next = NULL;
}
//求单链表长度
int getlength() {
Node *p = head->next;
int len = 0;
while (p) {
len++;
p = p->next;
}
return len;
}
//取第i个元素
bool getelem(int i, int &e) {
if (i<1 || i>getlength()) {
return false;
}
Node *p = head->next;
int j = 1;
while (j<i) {
p = p->next;
j++;
}
e = p->data;
return true;
}
//查找元素e的位置
int locateelem(int e) {
Node *p = head->next;
int i = 1;
while (p) {
if (p->data == e) {
return i;
}
p = p->next;
i++;
}
return -1;
}
//插入元素
bool listinsert(int i, int e) {
if (i<1 || i>getlength() + 1) {
return false;
}
Node *p = head;
int j = 0;
while (j<i - 1) {
p = p->next;
j++;
}
Node *s = new Node;
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
//删除元素
bool listdelete(int i, int &e) {
if (i<1 || i>getlength()) {
return false;
}
Node *p = head;
int j = 0;
while (j<i - 1) {
p = p->next;
j++;
}
Node *q = p->next;
e = q->data;
p->next = q->next;
delete q;
return true;
}
//修改元素
bool listmodify(int i, int e) {
if (i<1 || i>getlength()) {
return false;
}
Node *p = head->next;
int j = 1;
while (j<i) {
p = p->next;
j++;
}
p->data = e;
return true;
}
//输出链表
void output() {
Node *p = head->next;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.listinsert(1, 10);
list.listinsert(2, 20);
list.listinsert(3, 30);
list.listinsert(4, 40);
cout << "链表长度为:" << list.getlength() << endl;
cout << "第2个元素为:" << list.getelem(2) << endl;
int e;
cout << "元素30在链表中的位置为:" << list.locateelem(30) << endl;
list.listmodify(3, 50);
cout << "修改后的链表为:";
list.output();
list.listdelete(2, e);
cout << "删除的元素为:" << e << endl;
cout << "删除后的链表为:";
list.output();
return 0;
}
```
该程序实现了带头结点的单链表的建立、求长度、取元素、修改元素、插入、删除等基本操作。
阅读全文