單向鏈表

什么數(shù)據(jù)結(jié)構(gòu)最優(yōu)美,有人回答是數(shù)組。誠(chéng)然,數(shù)組是很多數(shù)據(jù)結(jié)構(gòu)的基礎(chǔ),就好比C語言在語言中的地位。但是當(dāng)你做WEB開發(fā)的時(shí)候會(huì)用C語言來寫嗎?數(shù)組是程序設(shè)計(jì)語言中提供的非常有用的數(shù)據(jù)結(jié)構(gòu),但是,數(shù)組至少有兩個(gè)局限性:
(1)編譯期要知道大小;
(2)數(shù)組中的數(shù)據(jù)在計(jì)算機(jī)內(nèi)存中是以相同距離間隔開的,這意味著在數(shù)組中插入一個(gè)數(shù)據(jù),需要移動(dòng)該數(shù)組中的其它數(shù)據(jù)。
鏈表就不存在這些問題,鏈表是節(jié)點(diǎn)的集合,節(jié)點(diǎn)中儲(chǔ)存著數(shù)據(jù)并連接到其它節(jié)點(diǎn)。分享一個(gè)新加坡一所學(xué)校做的很可愛的學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)的網(wǎng)站VisuAlgo
下面是保存整數(shù)單向鏈表的實(shí)現(xiàn):

//*************************intSLList.h*******************
//        singly-linked list class to store intergers
#ifndef DOUBLY_LINKED_LIST
#define DOUBLY_LINKED_LIST

 class IntSLLNode{
 public: IntSLLNode(){ 
                       next = 0; 
               } 
               IntSLLNode(int el, IntSLLNode *ptr = 0){
                       info = el; next = ptr;
               } 
               int info;
               IntSLList *next; 
 }; 

class IntSLList{ 
public: IntSLList(){ 
                 head = tail = 0; 
              } 
              ~IntSLList();
               int isempty(){
                         return head == 0; 
              } 
              void addToHead(int); 
        //  void addToTail(int); 
              int deleteFromHead(); 
        //  int deleteFromTail();  
        //  void deleteNode(int); 
              bool isIntList(int) const; 
private:
             IntSLLNode *head, *tail; 
};
 #endif
//*********************intSLList.cpp********************
#include <iostream>
#include "intSLLint.h"

IntSLList::~IntSLList(){
         for (IntSLLNode *p; !isEmpty(); ){
               p = head -> next;
               delete head;
               head = p;
         }
}
void IntSLList::addToHead (int el){
         head = new IntSLLNode (int el);
         if (tail = 0)
               tail = head;
}
int IntSLList::deleteFromHead(){
        int el = head ->info;
        IntSLLNode *tmp = head;
        if (head == tail)
               head = tail = 0;
        else head = head ->next;
        delete tmp;
        return el;
}
bool IntSLList::isInList(int el) const{
        IntSLLNode *tmp;
        for (tmp = head; tmp != 0 && !(tmp ->info ==el); tmp = tmp ->next);
        return tmp != 0;
}

其中實(shí)現(xiàn)了在鏈表的前面添加一個(gè)節(jié)點(diǎn),在鏈表的前面刪除一個(gè)節(jié)點(diǎn)以及查找;在鏈表的末尾添加/刪除以及刪除保存某個(gè)整數(shù)的節(jié)點(diǎn)的函數(shù)沒有寫出,道理差不多。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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