#include

// 节点类 class Node { public: int data; Node* prev; Node* next; };

// 链表类 class LinkedList { public: LinkedList(); ~LinkedList();

void insert(int data, int position);
void remove(int position);
Node* search(int data);
void display();
void displayBinary(); // 添加显示二进制的函数

private: Node* head; };

// 构造函数 LinkedList::LinkedList() { head = nullptr; }

// 析构函数 LinkedList::~LinkedList() { Node* current = head; while (current != nullptr) { Node* next = current->next; delete current; current = next; } }

// 在指定位置插入元素 void LinkedList::insert(int data, int position) { Node* newNode = new Node(); newNode->data = data;

if (head == nullptr) {
    head = newNode;
    return;
}

if (position == 0) {
    newNode->next = head;
    head->prev = newNode;
    head = newNode;
    return;
}

Node* current = head;
int count = 0;
while (count < position - 1 && current->next != nullptr) {
    current = current->next;
    count++;
}

newNode->prev = current;
newNode->next = current->next;
if (current->next != nullptr) {
    current->next->prev = newNode;
}
current->next = newNode;

}

// 移除指定位置的元素 void LinkedList::remove(int position) { if (head == nullptr) { return; }

if (position == 0) {
    Node* temp = head;
    head = head->next;
    if (head != nullptr) {
        head->prev = nullptr;
    }
    delete temp;
    return;
}

Node* current = head;
int count = 0;
while (count < position && current != nullptr) {
    current = current->next;
    count++;
}

if (current == nullptr) {
    return;
}

current->prev->next = current->next;
if (current->next != nullptr) {
    current->next->prev = current->prev;
}
delete current;

}

// 查找指定的元素 Node* LinkedList::search(int data) { Node* current = head; while (current != nullptr) { if (current->data == data) { return current; } current = current->next; } return nullptr; }

// 显示链表内容 void LinkedList::display() { Node* current = head; while (current != nullptr) { std::cout << current->data << " "; current = current->next; } std::cout << std::endl; }

// 以二进制方式显示链表存储内容 void LinkedList::displayBinary() { Node* current = head; while (current != nullptr) { std::cout << "节点数据: " << std::bitset<sizeof(int) * 8>(current->data) << std::endl; std::cout << "前驱指针: " << std::bitset<sizeof(Node*) * 8>(current->prev) << std::endl; std::cout << "后继指针: " << std::bitset<sizeof(Node*) * 8>(current->next) << std::endl; current = current->next; } }

int main() { LinkedList list;

list.insert(1, 0);
list.insert(2, 1);
list.insert(3, 2);
list.insert(4, 1);

std::cout << "链表内容: ";
list.display();  // 输出:1 4 2 3

std::cout << "删除位置2后的链表内容: ";
list.remove(2);
list.display();  // 输出:1 4 3

Node* result = list.search(4);
if (result != nullptr) {
    std::cout << "元素已找到: " << result->data << std::endl;  // 输出:元素已找到: 4
} else {
    std::cout << "元素未找到." << std::endl;
}

std::cout << "链表存储的二进制表示: " << std::endl;
list.displayBinary();

return 0;

}

C++自定义数据结构:双向链表实现及二进制存储显示

原文地址: https://www.cveoy.top/t/topic/pywW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录