鍊錶想象成火車,火車頭看做是鍊錶的表頭,車廂裡載的人和物就是元素的資料域
連線車廂的不見就是元素指標,由此,鍊錶的特點是:元素之間前後依賴,串聯而成
還有,我們可以發現,鍊錶的元素不能隨機訪問,在火車中行走,只能挨個走過去,而不能直接跳過去
另外,除了火車頭,每節車廂前面之連線一節車廂;除了最後的車廂。這也是鍊錶的特點:
元素前面和後面不會出現多個元素相連的情況
找到鍊錶中要插入的位置
令待插入結點的next指標指向插入位置的當前節點
令插入位置之前的當前節點的next指標指向待插入結點
插入需要插入在指定位置之前:
鍊錶的插入分為三個階段:
頭為空:將插入的新元素標誌為頭(注意index 要等於0)
只有乙個頭的鍊錶:將新節點放到頭後面,同時把新節點標誌為頭
遍歷操作:index表示要插入的位置,也表示插入後新元素所在的位置
首先遍歷到要被插入元素的前乙個元素,然後使新節點指向原index指點
前乙個元素指向新節點
鍊錶的刪除操作:
從表頭遍歷找到要刪除的位置
令刪除位置前乙個節點的next指標指向待刪除位置後乙個節點
刪除節點
翻轉鍊錶:
定義乙個用於遍歷的指標,初始指向頭節點後乙個節點
讓頭節點的next指標制空
從當前遍歷指標所指的節點開始遍歷鍊錶,將遍歷到的節點next指標指向頭節點。遍歷過程中借助另外乙個指標儲存下乙個遍歷到的節點
重複步驟3直至表尾,此時新鍊錶就是原鍊錶反轉後的鍊錶
#includeusing namespace std;
// 請在下面實現結點類 node
//一般涉及到遍歷或者刪除的操作:一般都要考慮->next
templateclass node
};// 請在下面實現鍊錶類 linkedlist
templateclass linkedlist
~linkedlist()
} //鍊錶的插入
void insert(node* node, int index);
void output();
void deletenode(int index);
void reverse();
};templatevoid linkedlist::reverse() //列表的反轉操作
}templatevoid linkedlist::deletenode(int index)
//(2)刪除頭節點 index=0;
if (index == 0)
//(3)正常刪除操作
node* current_node = head;
int count = 0;
//移動到前乙個節點
while (current_node->next != nullptr && count < index - 1)
//刪除操作
if (count == index - 1 && current_node->next != nullptr)
}//鍊錶的遍歷
templatevoid linkedlist::output()
node* current_node = head;
while (current_node != nullptr)
cout << endl;
}templatevoid linkedlist::insert(node* node, int index)
//情況2 只存在乙個表頭(插入表頭)
if (index == 0)
//情況3 插入到中間
//從頭開始遍歷
node* current_node = head;
int count = 0;
while (current_node->next != nullptr && count < index - 1)
if (count == index - 1)
}int main()
linkedlist.output();
linkedlist.deletenode(3);
linkedlist.output();
linkedlist.reverse();
linkedlist.output();
system("pause");
return 0;
}
c 模板鍊錶實現
簡介 主要是利用模板實現鍊錶的操作。模板的使用,使得程式的開發量大大地減少。可以先定義乙個鍊錶linklist,之後可以定義自己的類了 例如 student類 使用時就可以這樣呼叫了 linklistl 下面便是鍊錶的實現 linklist.cpp templatestruct node templ...
C 實現鍊錶(模板)
pragma once include includeusing namespace std template 定義節點 class node 定義鍊錶 templateclass linklist linklist 無參 head nullptr 拷貝構造 linklist const linkl...
模板類實現鍊錶
原創 我們在很多情況下會遇到這樣的情況,比如說,乙個鍊錶,他的資料型別有int,char,double等,這個時候我們可能直觀的理解就是建立多個struct node 這樣固然能狗解決問題,但是這並不可取,太過死板,這時候利用c 中的模板,可以很好的解決這一問題 關於模板那裡的東西,可以檢視相關的書...