Javascript 实现链表的常见操作
1. 单链表反转
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var reverseList = function (head) { if (!head || !head.next) { return head; } let preNode = null; let currentNode = head; let nextNode = currentNode.next; while (currentNode.next) { currentNode.next = preNode; preNode = currentNode; currentNode = nextNode; nextNode = currentNode.next; } // 此时,currentNode 为最后一个节点 currentNode.next = preNode; return currentNode; };
2. 链表中环的检测
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {boolean} */ var hasCycle = function (head) { let slowP = head; let fastP = head; if (!head || !head.next) { return false; } // 链表中如果存在环,则两个指针早晚会相遇的! while (fastP.next && fastP.next.next) { slowP = slowP.next; fastP = fastP.next.next; if (slowP === fastP) { return true; } } return false; };
3. 两个有序的链表合并
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function (l1, l2) { if (!l1) { return l2; } if (!l2) { return l1; } let result = new ListNode(); let temp = result; while (l1 && l2) { if (l1.val <= l2.val) { temp.next = l1; l1 = l1.next; } else { temp.next = l2; l2 = l2.next; } temp = temp.next; } if (l1) { temp.next = l1; } if (l2) { temp.next = l2; } return result.next; };
4. 删除链表倒数第 n 个结点
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} n * @return {ListNode} */ var removeNthFromEnd = function (head, n) { let preHead = new ListNode(); preHead.next = head; let slowP = preHead; let fastP = preHead; let i = 0; if (!head) { return head; } while (fastP.next) { // 在 fastP 已经走了 n 步以后,slowP 才开始向前走 if (i >= n) { slowP = slowP.next; } i++; fastP = fastP.next; } slowP.next = slowP.next.next; return preHead.next; };
5. 求链表的中间结点
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var middleNode = function (head) { let slowP = head; let fastP = head; if(!head){ return head; } while (fastP && fastP.next) { slowP = slowP.next; fastP = fastP.next.next; } return slowP; };
下一篇:
前端的设计模式(列举9种