203. 移除链表元素
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
新建链表-遍历法
let result = new ListNode()let curr = resultif(!head){return head}while(head != null){if(head.val != val){curr.next = headcurr = curr.next}head = head.next}curr.next = nullreturn result.next
双指针解法
总结:新知识,哨兵节点,防止第一个节点是要删除的节点
/*** @param {ListNode} head* @param {number} val* @return {ListNode}*/var removeElements = function (head, val) {// 双指针let sentry = new ListNode() //哨兵sentry.next = head// 哨兵节点防止第一个节点为要删除的节点let prev = sentrylet next = sentry.next// 遍历while(next != null){if(next.val == val){prev.next = next.next} else {prev = next}next = next.next}return sentry.next};
递归
总结:对递归三部曲的了解还是不够,什么时候需要调用自身函数,什么时候需要返回数据
var removeElements = function (head, val) {// 递归// 1.结束条件if(head == null){return head}// 2.函数主功能head.next = removeElements(head.next,val)// 3.函数等价式return head.val === val ? head.next : head};
剑指 Offer II 026. 重排链表
给定一个单链表 L 的头节点 head ,单链表 L 表示为:L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

/*** Definition for singly-linked list.* function ListNode(val, next) {* this.val = (val===undefined ? 0 : val)* this.next = (next===undefined ? null : next)* }*//*** @param {ListNode} head* @return {void} Do not return anything, modify head in-place instead.*/var reorderList = function (head) {// 快慢指针寻找到链表中心节点let fast = headlet slow = headwhile (fast != null && fast.next != null) {fast = fast.next.nextslow = slow.next}// 反转后半部分的链表let newList = reverseList(slow)let prev = head// 将后半部分的链表插入前部分while (newList.next != null) {let curr = newListnewList = newList.nextcurr.next = prev.nextprev.next = currprev = curr.next}return head};let reverseList = function (head) {if (head == null || head.next == null) {return head}let newList = reverseList(head.next)head.next.next = headhead.next = nullreturn newList}
