鏈表復(fù)習(xí)(一)

鏈表性質(zhì)——此處略

簡單的鏈表基本結(jié)構(gòu)(cpp):

#include<iostream>
using namespace std;
class Node {
public:
    int data;
    Node* next;
    Node(int _data) {
        data = _data;
        next = NULL;
    }
};
class LinkList {
private:
    Node* head;
public:
    LinkList() {
        head = NULL;
    }

};
int main() {
    LinkList linklist;
    return 0;
}

實現(xiàn)鏈表插入函數(shù)——參數(shù)為Node*和int,分別表示要插入的節(jié)點和插入節(jié)點的Index,即插入節(jié)點后的節(jié)點為第Index個節(jié)點

void insert(Node* node,int index){
        if(head==NULL){//第一種情況——原鏈表為空,直接把head設(shè)置為node
            head=node;
            return;
        }
        if(index==0){//第二種情況:index=0.也就是把node插入到鏈表的首位,直接把head接在node上,然后把node設(shè)置成head
            node->next=head;
            head=node;
            return;
        }
        int count=0;
        Node* current_node=head;
        while(current_node->next!=NULL&&count<index-1){
            current_node=current_node->next; //遍歷鏈表尋找index的前一位
            count++;
        }    
        if(count==index-1){
            node->next=current_node->next;//先把node的下一位設(shè)置成current的下一位,然后再把current的下一位設(shè)置成node,注意順序不能變
            current_node->next=node;
        }

}

總結(jié)整個插入操作流程:

1、首先檢查鏈表是否為空,如果為空則直接把node設(shè)置為head

2、檢查index是否為0,若為0則表示將node插入到鏈表的首位——直接把node設(shè)置成head前一位,然后更新head為node即可

3、建立一個指針指向當(dāng)前節(jié)點,同時附帶一個計數(shù)器,依次遍歷鏈表尋找index的前一位(即index-1)

4、檢查count==index-1以確保index的值合法,然后執(zhí)行插入操作:把node的下一位設(shè)置成current的下一位,然后更新current的下一位為node,注意順序不能亂

遍歷輸出函數(shù)(解說略)

void output(){
        Node* current_node;
        if(head!=NULL){
            current_node=head;
        }
        else{
            return;
        }
        while(current_node!=NULL){
            cout<<current_node->data<<endl;
            current_node=current_node->next;
        }
        cout<<endl;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容