js 单向链表的实现

1,896 阅读1分钟

省略校验等步骤,只是简单实现而已

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */

// 节点表示
function ListNode(val) {
    this.val = val;
    this.next = null;
}

// 在链表末尾添加节点
function addNode(num, listNode) {
    // 如果原始链表为空,则新建一个
    if(listNode === null) return new ListNode(num);
    // 添加节点
    let curNode = listNode;
    while(curNode.next !== null) {
        curNode = curNode.next;
    }
    curNode.next = new ListNode(num);
}

// 删除链表末尾节点
function removeNode(listNode) {
    while(listNode.next !== null) {
        if(listNode.next.next === null) break;
        listNode = listNode.next;
    }
    listNode.next = null; 
}

// 挨个读取节点
function readNode(listNode) {
    while(listNode) {
        console.log(listNode.val);
        listNode = listNode.next;
        if(listNode) console.log('---->');
    }
} 

let listNode = new ListNode(1);
addNode(2, listNode);
addNode(3, listNode);
addNode(4, listNode);
addNode(5, listNode);
readNode(listNode);

removeNode(listNode);
readNode(listNode);

/**
output1: 
1
---->
2
---->
3
---->
4
---->
5

output2:
1
---->
2
---->
3
---->
4
*/