Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
2.6 kB
2
Indexable
Never

struct LinkedList {
    int val;
    LinkedList* next;
    LinkedList() {
        this->val = 0;
        this->next = nullptr;
    }
    LinkedList(int val) {
        this->val = val;
        this->next = nullptr;
    }
};

class MyLinkedList {
public:
    LinkedList* head;
    MyLinkedList() { head = nullptr; }

    int get(int index) {
        LinkedList* curr = head;
        while (curr && index--) {
            curr = curr->next;
            cout << "9";
        }
        cout << endl;
        // print(curr);
        if (index >= 0){

        cout << " ii " << index;
            return -1;
        }
        print(head);
        cout << curr->val;
        return curr->val;
    }

    void addAtHead(int val) {
        LinkedList* curr = new LinkedList(val);
        if (!head) {
            head = curr;
            return;
        }
        curr->next = head;
        head = curr;
    }

    void addAtTail(int val) {
        LinkedList* curr = head;
        while (curr && curr->next) {
            curr = curr->next;
        }
        LinkedList* newNode = new LinkedList(val);
        if (!curr) {
            head = newNode;
            return;
        }
        curr->next = newNode;
    }

    void addAtIndex(int index, int val) {
        if (!index) {
            addAtHead(val);
            return;
        }

        LinkedList* curr = head;
        while (curr && curr->next && --index) {
            curr = curr->next;
        }

        cout << " iii " << index ;

        if (index >= 0) return;

        LinkedList* newNode = new LinkedList(val);
        if (!curr) {
            head = newNode;
            return;
        }

        LinkedList* temp = curr->next;
        curr->next = newNode;
        newNode->next = temp;
        cout << "jhgjhgjg";
        print(head);
    }

    void deleteAtIndex(int index) {
        if (!head) return;
        if (!index) {
            head = head->next;
            return;
        }

        LinkedList* curr = head;
        while (curr->next && index--) {
            curr = curr->next;
        }

        if (index >= 0) return;

        curr->next = curr->next->next;
    }

    void print(LinkedList* head) {
        while (head) {
            cout << head->val << " ";
            head = head->next;
        }
        cout << endl;
    }
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList* obj = new MyLinkedList();
 * int param_1 = obj->get(index);
 * obj->addAtHead(val);
 * obj->addAtTail(val);
 * obj->addAtIndex(index,val);
 * obj->deleteAtIndex(index);
 */v
Leave a Comment