带头结点的循环双链表的查找序号为i的元素,查找第一个值为x的元素,插入第i个元素,删除第i个元素的程序,c++实现
时间: 2024-02-28 20:56:13 浏览: 70
用C++编程实现链表删除某结点
5星 · 资源好评率100%
以下是带头结点的循环双链表的C++实现,包括了查找序号为i的元素,查找第一个值为x的元素,插入第i个元素,删除第i个元素的操作:
```c++
#include <iostream>
using namespace std;
// 双链表结构体
struct ListNode {
int val;
ListNode *prev, *next;
ListNode(int x) : val(x), prev(NULL), next(NULL) {}
};
// 带头结点的双链表类
class DoubleLinkedList {
private:
ListNode *head;
int size;
public:
// 构造函数,初始化头结点
DoubleLinkedList() {
head = new ListNode(0);
head->prev = head;
head->next = head;
size = 0;
}
// 获取链表长度
int getSize() {
return size;
}
// 查找序号为i的元素
ListNode* get(int i) {
if (i < 0 || i >= size) {
return NULL;
}
ListNode *cur = head->next;
for (int j = 0; j < i; j++) {
cur = cur->next;
}
return cur;
}
// 查找第一个值为x的元素
ListNode* search(int x) {
ListNode *cur = head->next;
while (cur != head) {
if (cur->val == x) {
return cur;
}
cur = cur->next;
}
return NULL;
}
// 在第i个位置插入元素
bool insert(int i, int x) {
if (i < 0 || i > size) {
return false;
}
ListNode *cur = head->next;
for (int j = 0; j < i; j++) {
cur = cur->next;
}
ListNode *node = new ListNode(x);
node->prev = cur->prev;
node->next = cur;
cur->prev->next = node;
cur->prev = node;
size++;
return true;
}
// 删除第i个元素
bool remove(int i) {
if (i < 0 || i >= size) {
return false;
}
ListNode *cur = head->next;
for (int j = 0; j < i; j++) {
cur = cur->next;
}
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
delete cur;
size--;
return true;
}
};
int main() {
DoubleLinkedList list;
list.insert(0, 1);
list.insert(1, 2);
list.insert(2, 3);
list.insert(3, 4);
list.insert(4, 5);
ListNode *node = list.get(2);
if (node != NULL) {
cout << "Node at position 2: " << node->val << endl;
}
node = list.search(3);
if (node != NULL) {
cout << "Node with value 3 found at position: " << (node - list.get(0)) << endl;
}
list.insert(2, 6);
cout << "List after insertion: ";
for (int i = 0; i < list.getSize(); i++) {
cout << list.get(i)->val << " ";
}
cout << endl;
list.remove(3);
cout << "List after deletion: ";
for (int i = 0; i < list.getSize(); i++) {
cout << list.get(i)->val << " ";
}
cout << endl;
return 0;
}
```
需要注意的是,在实现查找序号为i的元素时,如果i超出了链表的范围,返回的是NULL;在实现查找第一个值为x的元素时,如果链表中不存在值为x的元素,也返回NULL。在插入和删除元素时,需要注意更新链表的大小。
阅读全文