c_cpp 链接列表实现与类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 链接列表实现与类相关的知识,希望对你有一定的参考价值。

#include<bits/stdc++.h>
using namespace std;

class node {
public:
    int data;
    node* next;
    node (){
        data = 0;
        next = NULL;
    }
    node (int x){
        data = x;
        next = NULL;
    }
};

class ll{
public:
    node* head;
    ll(){
        head = NULL;
    }

    bool isEmpty (){
        if (head == NULL){
            return true;
        }
        return false;
    }

    node* getLastNode(){
        if (head == NULL){
            return head;
        }else{
            node* temp = head;
            while (temp->next != NULL){
                temp = temp->next;
            }
            return temp;
        }
    }

    void printll(){
        if (head == NULL){
            cout<<"Empty List"<<endl;
        }else{
            node* temp = head;
            while (temp != NULL){
                cout<<temp->data<<" ";
                temp = temp->next;
            }
        }
        cout<<endl;
    }

    void addAtFront(int x){
        node* n = new node(x);
        if (head == NULL){
            head = n;
        }else{
            n->next = head;
            head = n;
        }
    }

    void addAtLast(int x){
        node* n = new node(x);
        if (head == NULL){
            head = n;
        }else{
            node* last = getLastNode();
            last->next = n;
        }
    }

    bool delAtFront(){
        if (head == NULL){
            return false;
        }else{
            node* temp = head;
            head = temp->next;
            delete (temp);
            return true;
        }
    }

    bool delAtLast(){
        if (head == NULL){
            return false;
        }else{
            node* temp = getLastNode();
            delete (temp);
            return true;
        }
    }

    void Insert (int x, int n){
        if (n == 1){
            addAtFront(x);
        }else{
            node* temp = new node(x);
            node* temp1 = head;
            int i=2;
            while (i<n){
                temp1 = temp1->next;
                i++;
            }
            temp->next = temp1->next;
            temp1->next = temp;
        }
    }

    bool Delete (int n){
        if (n == 1){
            return delAtFront();
        }else{
            node *h = head;
            for (int i=0; i<n-2; i++){
                h = h->next;
            }
            node* temp = h->next;
            h->next = temp->next;
            delete(temp);
            return true;
        }
    }
};

int main (){
    ll l1;
    l1.addAtLast(5);
    l1.addAtLast(4);
    l1.addAtLast(6);
    l1.addAtLast(2);
    l1.addAtFront(3);
    l1.printll();
    l1.Insert(1,1);
    l1.Insert(2,3);
    l1.printll();
    l1.Delete(3);
    l1.printll();
    return 0;
}

以上是关于c_cpp 链接列表实现与类的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 链接列表的线性队列实现

c_cpp 使用Struct实现链接列表

c_cpp 使用类和链接列表实现堆栈

c_cpp 队列 - C ++中的链接列表实现

c_cpp 链接列表

c_cpp 旋转链接列表