介绍

实现链表的创建,查找,增加,删除操作,打印。

完整代码

#include <iostream>

using namespace std;

class Node{
private:
    int data;
    Node *next;
public:
    Node(){
        next = NULL;
    }
    friend class linkList;
};

class linkList{
private:
    Node *head;
    int length;
public:
    linkList(){
        head = new Node;
        length = 0;
    }
    void creatList(int length){
        Node *p = head;
        for(int i = 1; i <= length; i++){
            Node *newNode = new Node;
            cin >> newNode->data;
            p->next = newNode;
            p = newNode;
        }
        this->length = length;
    }
    void append(int data){
        Node *p = head;
        while(p->next != NULL) p = p->next;
        Node *newNode = new Node;
        cin >> newNode->data;
        p->next = newNode;
        length++;
    }
    Node* find(int data){
        Node *p = head;
        while(p->next != NULL){
            if(p->next->data == data) return p;
            p = p->next;
        }
        return NULL;
    }
    void remove(int data){
        Node *p = find(data);
        if(p == NULL) return;
        Node *deleteNode = p->next;
        p->next = deleteNode->next;
        delete deleteNode;
        length--;
    }
    void printList(){
        Node *p = head->next;
        while(p != NULL){
            cout << p->data << " ";
            p = p->next;
        }
        cout << endl;
    }
    int getLength(){
        return length;
    }
};

int main()
{
    linkList L;
    L.creatList(3);
    L.remove(2);
    L.printList();
    return 0;
}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐