We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原题链接
先明确,删除倒数第 n 个结点,我们需要找到倒数第 n+1 个结点,删除其后继结点即可。
1.添加 prev 哨兵结点,处理边界问题。 2.借助快慢指针,快指针先走 n+1 步,然后快慢指针同步往前走,直到 fast.next 为 null。 3.删除倒数第 n 个结点,返回 prev.next。
const removeNthFromEnd = function(head, n) { let prev = new ListNode(0), fast = prev, slow = prev; prev.next = head; while (n--) { fast = fast.next; } while (fast && fast.next) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return prev.next; }
The text was updated successfully, but these errors were encountered:
//老师指导一下呗 // 感觉我写的不是很易懂,快慢指针好太多了~哎 /* * @lc app=leetcode.cn id=19 lang=javascript * * [19] 删除链表的倒数第 N 个结点 */ // @lc code=start /** * 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 $head = head; // 获取长度 let len = 1; while($head.next) { $head = $head.next; len++; } let use = len - n; if (use == 0) { return head.next; } $head = head; while (use > 1) { $head = $head.next; use--; } $head.next = $head.next.next; return head; }; // @lc code=end
Sorry, something went wrong.
No branches or pull requests
原题链接
快慢指针
先明确,删除倒数第 n 个结点,我们需要找到倒数第 n+1 个结点,删除其后继结点即可。
1.添加 prev 哨兵结点,处理边界问题。
2.借助快慢指针,快指针先走 n+1 步,然后快慢指针同步往前走,直到 fast.next 为 null。
3.删除倒数第 n 个结点,返回 prev.next。
The text was updated successfully, but these errors were encountered: