溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

指針函數(shù)在鏈表操作中的實(shí)現(xiàn)

發(fā)布時(shí)間:2024-08-04 12:26:05 來(lái)源:億速云 閱讀:88 作者:小樊 欄目:編程語(yǔ)言

在鏈表操作中,指針函數(shù)通常用于實(shí)現(xiàn)對(duì)鏈表節(jié)點(diǎn)的操作,比如插入、刪除、查找等功能。以下是一個(gè)簡(jiǎn)單的鏈表操作示例,包括創(chuàng)建鏈表、插入節(jié)點(diǎn)、刪除節(jié)點(diǎn)和打印鏈表的過(guò)程:

#include <iostream>

struct Node {
    int data;
    Node* next;
};

Node* createNode(int data) {
    Node* newNode = new Node();
    newNode->data = data;
    newNode->next = nullptr;
    return newNode;
}

void insertNode(Node** head, int data) {
    Node* newNode = createNode(data);
    newNode->next = *head;
    *head = newNode;
}

void deleteNode(Node** head, int data) {
    Node* temp = *head;
    Node* prev = nullptr;

    if (temp != nullptr && temp->data == data) {
        *head = temp->next;
        delete temp;
        return;
    }

    while (temp != nullptr && temp->data != data) {
        prev = temp;
        temp = temp->next;
    }

    if (temp == nullptr) {
        return;
    }

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

void printList(Node* head) {
    Node* temp = head;
    while (temp != nullptr) {
        std::cout << temp->data << " ";
        temp = temp->next;
    }
    std::cout << std::endl;
}

int main() {
    Node* head = nullptr;

    insertNode(&head, 3);
    insertNode(&head, 5);
    insertNode(&head, 7);

    printList(head);

    deleteNode(&head, 5);

    printList(head);

    return 0;
}

在上面的示例中,我們定義了一個(gè)結(jié)構(gòu)體 Node 表示鏈表節(jié)點(diǎn),然后實(shí)現(xiàn)了創(chuàng)建節(jié)點(diǎn)、插入節(jié)點(diǎn)、刪除節(jié)點(diǎn)和打印鏈表的函數(shù)。在主函數(shù)中,我們創(chuàng)建了一個(gè)鏈表,并進(jìn)行了插入和刪除節(jié)點(diǎn)的操作,最后打印鏈表的內(nèi)容。通過(guò)指針函數(shù)的使用,我們可以方便地對(duì)鏈表進(jìn)行各種操作。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI