leetcode算法題--設計鏈表

原題鏈接:https://leetcode-cn.com/problems/design-linked-list/

class MyListNode{
    public:
            int val;
            MyListNode *next;
            MyListNode(int x){
                val=x;
                next=NULL;
            }
};

class MyLinkedList:public ListNode{
public:
    /** Initialize your data structure here. */
    MyListNode *head;
    MyLinkedList() {
        head=NULL;
    }
    
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    int get(int index) {
        MyListNode *p=this->head;
        while(index>0&&p!=NULL){
            index--;
            p=p->next;
        }
        if(index==0&&p!=NULL) return p->val;
        else return -1;
    }
    
    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    void addAtHead(int val) {
        MyListNode *dummy=new MyListNode(val);
        dummy->next=this->head;
        this->head=dummy;
    }
    
    /** Append a node of value val to the last element of the linked list. */
    void addAtTail(int val) {
        MyListNode *p=this->head;
        while(p->next!=NULL) p=p->next;
        p->next=new MyListNode(val);
    }
    
    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    void addAtIndex(int index, int val) {
        if(index<=0) addAtHead(val);
        MyListNode *p=this->head;
        while(index>1&&p!=NULL){
            index--;
            p=p->next;
        }
        if(p!=NULL){
            MyListNode *tmp=new MyListNode(val);
            tmp->next=p->next;
            p->next=tmp;
        }
    }
    
    /** Delete the index-th node in the linked list, if the index is valid. */
    void deleteAtIndex(int index) {
        MyListNode *p=this->head;
        if(index==0){
            this->head=p->next;
            p->next=NULL;
            return;
        }
        MyListNode *pre;
        while(index>0&&p!=NULL){
            index--;
            pre=p;
            p=p->next;
        }
        if(index==0&&p!=NULL){
            pre->next=p->next;
            delete p;
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章