javaScript的數(shù)據(jù)結(jié)構(gòu)與算法(二)——鏈表

1、鏈表

鏈表存儲有序的元素集合阐滩,但不同于數(shù)組二打,鏈表中的元素在內(nèi)存中并不是連續(xù)放置的。每個元素由一個存儲元素本事的節(jié)點和一個指向下一個元素的引用組成叶眉。相對于傳統(tǒng)的數(shù)組址儒,鏈表的一個好處在于,添加或者刪除元素的時候不需要移動其他元素衅疙。然而,鏈表需要使用指針鸳慈,因此實現(xiàn)鏈表時需要額外注意饱溢。

數(shù)組和鏈表的一個不同在于數(shù)組可以直接訪問任何位置的元素,而想要訪問鏈表中的一個元素走芋,需要從起點開始迭代列表绩郎。

1.1、單向鏈表

下面是單向鏈表的具體實現(xiàn)代碼:

function LinkedList() {
    var Node = function(element){
        this.element = element;
        this.next = null;
    };
    var length = 0;//鏈表長度
    var head = null;//第一個節(jié)點
    this.append = function(element){
        var node = new Node(element),
            current;
        if (head === null){ //列表為空
            head = node;
        } else { //列表不為空
            current = head; //現(xiàn)在只知道第一項head
            while(current.next){ //找到列表的最后一項
                current = current.next;
            }
            //建立鏈接
            current.next = node;
        }
        length++; //更新列表長度
    };
    this.insert = function(position, element){
        //檢查越界值
        if (position >= 0 && position <= length){
            var node = new Node(element),
                current = head,
                previous,
                index = 0;
            if (position === 0){ //在第一個位置添加
                node.next = current;
                head = node;
            } else { //在中間或者尾部添加
                while (index++ < position){
                    previous = current;
                    current = current.next;
                }
                node.next = current; //先連上添加的節(jié)點
                previous.next = node; //再斷開之前的連接
            }
            length++; 
            return true;
        } else {
            return false;
        }
    };
    this.removeAt = function(position){
        if (position > -1 && position < length){
            var current = head,
                previous,
                index = 0; //用來迭代列表翁逞,直到到達目標(biāo)位置
            if (position === 0){ //移除第一項
                head = current.next;
            } else { //移除中間或者尾部最后一項
                while (index++ < position){
                    previous = current;
                    current = current.next;
                }
                //連接前一項和后一項肋杖,跳過當(dāng)前的項,相當(dāng)于移除了當(dāng)前項
                previous.next = current.next;
            }
            length--;
            return current.element;
        } else {
            return null;
        }
    };
    this.remove = function(element){
        var index = this.indexOf(element);
        return this.removeAt(index);
    };
    this.indexOf = function(element){
        var current = head,
            index = 0;
        while (current) {
            if (element === current.element) {
                return index;
            }
            index++; //記錄位置
            current = current.next;
        }
        return -1;
    };
    this.isEmpty = function() {
        return length === 0;
    };
    this.size = function() {
        return length;
    };
    this.getHead = function(){
        return head;
    };
    this.toString = function(){
        var current = head,
            string = '';
        while (current) {
            string += current.element;//拼接
            current = current.next;
        }
        return string;
    };
    this.print = function(){
        console.log(this.toString());
    };
}

1.2挖函、雙向鏈表

雙向鏈表和單向鏈表的區(qū)別在于状植,在單向鏈表中,一個節(jié)點只有鏈向下一個節(jié)點的鏈接。而在雙向鏈表中津畸,鏈接是雙向的:一個鏈向下一個元素振定,另一個鏈向前一個元素。示例代碼如下:

function DoublyLinkedList() {
    var Node = function(element){
        this.element = element;
        this.next = null;
        this.prev = null; //新添加的
    };
    var length = 0;
    var head = null;
    var tail = null; //新添加的
    this.append = function(element){
        var node = new Node(element),
            current;
        if (head === null){ //列表為空
            head = node;
            tail = node; 
        } else {
            tail.next = node;
            node.prev = tail;
            tail = node;
        }
        length++; 
    };
    this.insert = function(position, element){
        if (position >= 0 && position <= length){
            var node = new Node(element),
                current = head,
                previous,
                index = 0;
            if (position === 0){ //在第一個位置
                if (!head){       //列表為空
                    head = node;
                    tail = node;
                } else {      //列表不為空
                    node.next = current;
                    current.prev = node; 
                    head = node;
                }
            } else  if (position === length) { //最后一項
                current = tail;     
                current.next = node;
                node.prev = current;
                tail = node;
            } else {
                while (index++ < position){ 
                    previous = current;
                    current = current.next;
                }
                node.next = current;
                previous.next = node; //把node節(jié)點連接進去前一個節(jié)點和后一個節(jié)點

                current.prev = node; //斷掉之前previous和current的連接
                node.prev = previous; //prev同樣需要連接
            }
            length++; 
            return true;
        } else {
            return false;
        }
    };
    this.removeAt = function(position){
        if (position > -1 && position < length){
            var current = head,
                previous,
                index = 0;
            if (position === 0){ //移除第一項
                head = current.next; 
                if (length === 1){ // 列表只有一項
                    tail = null;
                } else {
                    head.prev = null; 
                }
            } else if (position === length-1){ 移除最后一項
                current = tail; // {4}
                tail = current.prev;
                tail.next = null;
            } else {
                while (index++ < position){ 
                    previous = current;
                    current = current.next;
                }
                previous.next = current.next; // 鏈接前一項和后一項肉拓,跳過當(dāng)前項
                current.next.prev = previous; //修復(fù)prev
            }
            length--;
            return current.element;
        } else {
            return null;
        }
    };
    this.remove = function(element){
        var index = this.indexOf(element);
        return this.removeAt(index);
    };
    this.indexOf = function(element){
        var current = head,
            index = -1;
        //檢查第一項
        if (element == current.element){
            return 0;
        }
        index++;
        //檢查中間項
        while(current.next){
            if (element == current.element){
                return index;
            }
            current = current.next;
            index++;
        }
        //檢查最后一項
        if (element == current.element){
            return index;
        }
        return -1;
    };
    this.isEmpty = function() {
        return length === 0;
    };
    this. size = function() {
        return length;
    };
    this.toString = function(){
        var current = head,
            s = current ? current.element : '';
        while(current && current.next){
            current = current.next;
            s += ', ' + current.element;
        }
        return s;
    };
    this.inverseToString = function() {
        var current = tail,
            s = current ? current.element : '';
        while(current && current.prev){
            current = current.prev;
            s += ', ' + current.element;
        }
        return s;
    };
    this.print = function(){
        console.log(this.toString());
    };
    this.printInverse = function(){
        console.log(this.inverseToString());
    };
    this.getHead = function(){
        return head;
    };
    this.getTail = function(){
        return tail;
    }
}

1.3后频、循環(huán)鏈表

循環(huán)鏈表可以像單向鏈表那樣只有單向引用,也可以像雙向鏈表那樣有雙向引用暖途。循環(huán)鏈表和其他鏈表的區(qū)別在于最后一個元素指向下一個元素的引用不是null卑惜,而是指向第一個元素(head)。示例代碼如下:

function CircularLinkedList() {
    var Node = function(element){
        this.element = element;
        this.next = null;
    };
    var length = 0;
    var head = null;
    this.append = function(element){
        var node = new Node(element),
            current;
        if (head === null){ //列表為空
            head = node;
        } else {
            current = head;
            while(current.next !== head){ //最后一個元素將是head驻售,而不是null
                current = current.next;
            }
            current.next = node; //建立連接
        }
        node.next = head; //首尾相連起來變成一個環(huán)列表
        length++; 
    };
    this.insert = function(position, element){
        if (position >= 0 && position <= length){
            var node = new Node(element),
                current = head,
                previous,
                index = 0;
            if (position === 0){ //在第一項
                node.next = current;
                while(current.next !== head){ 
                    current = current.next;
                }
                head = node;
                current.next = head;
            } else {
                while (index++ < position){
                    previous = current;
                    current = current.next;
                }
                node.next = current;
                previous.next = node;
                if (node.next === null){ //在最后一個元素更新
                    node.next = head;
                }
            }
            length++; 
            return true;
        } else {
            return false;
        }
    };
    this.removeAt = function(position){
        if (position > -1 && position < length){
            var current = head,
                previous,
                index = 0;
            if (position === 0){
                while(current.next !== head){ 
                    current = current.next;
                }
                head = head.next;
                current.next = head; //更新最后一項
            } else { 
                while (index++ < position){
                    previous = current;
                    current = current.next;
                }
                previous.next = current.next;
            }
            length--;
            return current.element;
        } else {
            return null;
        }
    };
    this.remove = function(element){
        var index = this.indexOf(element);
        return this.removeAt(index);
    };
    this.indexOf = function(element){
        var current = head,
            index = -1;
        if (element == current.element){ //檢查第一項
            return 0;
        }
        index++;
        while(current.next !== head){ //檢查列表中間
            if (element == current.element){
                return index;
            }
            current = current.next;
            index++;
        }
        if (element == current.element){ //檢查最后一項
            return index;
        }
        return -1;
    };
    this.isEmpty = function() {
        return length === 0;
    };
    this.size = function() {
        return length;
    };
    this.getHead = function(){
        return head;
    };
    this.toString = function(){
        var current = head,
            s = current.element;
        while(current.next !== head){
            current = current.next;
            s += ', ' + current.element;
        }
        return s.toString();
    };
    this.print = function(){
        console.log(this.toString());
    };
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末残揉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子芋浮,更是在濱河造成了極大的恐慌抱环,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件纸巷,死亡現(xiàn)場離奇詭異镇草,居然都是意外死亡,警方通過查閱死者的電腦和手機瘤旨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進店門梯啤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人存哲,你說我怎么就攤上這事因宇。” “怎么了祟偷?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵察滑,是天一觀的道長。 經(jīng)常有香客問我修肠,道長贺辰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任嵌施,我火速辦了婚禮饲化,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘吗伤。我一直安慰自己吃靠,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布足淆。 她就那樣靜靜地躺著巢块,像睡著了一般礁阁。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上夕冲,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天氮兵,我揣著相機與錄音,去河邊找鬼歹鱼。 笑死泣栈,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的弥姻。 我是一名探鬼主播南片,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼庭敦!你這毒婦竟也來了疼进?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤秧廉,失蹤者是張志新(化名)和其女友劉穎伞广,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體疼电,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡嚼锄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了蔽豺。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片区丑。...
    茶點故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖修陡,靈堂內(nèi)的尸體忽然破棺而出沧侥,到底是詐尸還是另有隱情,我是刑警寧澤魄鸦,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布宴杀,位于F島的核電站,受9級特大地震影響号杏,放射性物質(zhì)發(fā)生泄漏婴氮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一盾致、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧荣暮,春花似錦庭惜、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽惠遏。三九已至,卻和暖如春骏啰,著一層夾襖步出監(jiān)牢的瞬間节吮,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工判耕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留透绩,地道東北人。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓壁熄,卻偏偏與公主長得像帚豪,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子草丧,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容