javascript 数据结构 之 单链表

/**
 * Created by hatmore on 13-12-26.
 */

function LinkedList() {
    var count = 0;
    var head = null;

    this.getCount = function () {
        return count;
    }

    this.DisplayAll = function () {
        if (head === null) {
            return null;
        } else {
            var arr = [];
            var current = head;

            for (var i = 0; i < count; i++) {
                arr[i] = current.data;
                current = current.next;
            }
            return arr;
        }
    }

    this.DisplayAt = function () {
        if (index > -1 && index < count) {
            var current = head;
            var i = 0;

            while (i++ < index) {
                current = current.next;
            }
            return current.data;
        } else {
            return null;
        }
    }

    this.AddFirst = function (data) {
        var node = {
            data: data,
            next: head
        };

        head = node;

        count++;
    }

    this.Add = function (data, index) {

        if (index === 0) {
            this.AddFirst(data);
        } else if (index > -1 && index < count) {
            var node = {
                data: data,
                next: null
            };

            var previous;
            var current = head;
            var i = 0;

            while (i++ < index) {
                previous = current;
                current = current.next;
            }
            previous.next = node;
            node.next = current;
            count++;
        } else {
            alert("out of range");
        }
    }

    this.RemoveFirst = function () {
        if (head === null) {
            return null;
        } else {
            var out = head;
            head = head.next;

            if(count > 0) {
                count--;
            }
            return out.data;
        }
    }

    this.RemoveAt = function (index) {
        if (index === 0) {
            return this.RemoveFirst();
        }

        else if (index > -1 && index < count) {
            var current = head;
            var previous;
            var i = 0;

            while (i++ < index) {
                previous = current;
                current = current.next;
            }
            previous.next = current.next;
            count--;
        }else {
            return null;
        }
        return current.data;
    } 
}

你可能感兴趣的:(javascript 数据结构 之 单链表)