单链表实现增删改查遍历打印功能

下面是一个简单的单向链表实现,包括了增加、删除、修改和查找节点的基本操作函数。请注意,这里只是一个基础实现,并没有进行复杂的错误检查和异常处理。

#include <iostream>

// 定义链表节点结构体
struct Node {
    int data;       // 数据域
    Node* next;     // 指针域,指向下一个节点

    Node(int val) : data(val), next(NULL) {} // 构造函数
};

// 链表类
class LinkedList {
public:
    LinkedList() : head(NULL) {} // 构造函数

    void append(int value);
    void deleteNode(int value);
    void update(int oldValue, int newValue);
    bool find(int value);
    void printList();

private:
    Node* head; // 链表头指针
};

// 类成员函数的实现
void LinkedList::append(int value) {
    Node* newNode = new Node(value);
    if (head == NULL) {
        head = newNode;
    } else {
        Node* current = head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

void LinkedList::deleteNode(int value) {
    if (head == NULL) return;

    Node* temp = head;
    if (temp->data == value) {
        head = temp->next;
        delete temp;
        return;
    }

    Node* prev = NULL;
    while (temp != NULL && temp->data != value) {
        prev = temp;
        temp = temp->next;
    }

    if (temp == NULL) return;

    prev->next = temp->next;
    delete temp;
}

void LinkedList::update(int oldValue, int newValue) {
    Node* current = head;
    while (current != NULL) {
        if (current->data == oldValue) {
            current->data = newValue;
            return;
        }
        current = current->next;
    }
}

bool LinkedList::find(int value) {
    Node* current = head;
    while (current != NULL) {
        if (current->data == value) {
            return true;
        }
        current = current->next;
    }
    return false;
}

void LinkedList::printList() {
    Node* current = head;
    while (current != NULL) {
        std::cout << current->data << " -> ";
        current = current->next;
    }
    std::cout << "null" << std::endl;
}

int main() {
    LinkedList list;

    list.append(1);
    list.append(2);
    list.append(3);
    list.append(4);

    std::cout << "Initial list: ";
    list.printList();

    list.deleteNode(2);
    std::cout << "After deleting 2: ";
    list.printList();

    list.update(3, 30);
    std::cout << "After updating 3 to 30: ";
    list.printList();

    if (list.find(30)) {
        std::cout << "30 is found in the list." << std::endl;
    } else {
        std::cout << "30 is not found in the list." << std::endl;
    }

    return 0;
}

这个程序定义了一个链表类LinkedList,它包含了增加节点到尾部、删除节点、更新节点数据和查找节点数据的功能。在main函数中,我们创建了一个链表实例,对其进行了几个基本操作,并打印了操作后的链表状态。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九层指针

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>