-
Notifications
You must be signed in to change notification settings - Fork 634
New issue
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
leetcode876:求链表的中间结点 #15
Labels
Comments
var middleNode = function (head) {
if (!head) return []
var arr = []
while (head) {
arr.push(head)
head = head.next
}
return arr[Math.ceil((arr.length - 1) / 2)]
};
var middleNode = function (head) {
if (!head) return []
var fast = slow = head
while (fast && fast.next) {
slow = slow.next
fast = fast.next.next
}
return slow
}; |
快慢指针走一波 const getMiddleNode = function(head) {
if(!head) return null;
let fast = head.next.next, slow = head.next;
while(fast && fast.next) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}; |
都是快慢指针... var middleNode = function(head) {
let end = head, half = head
while(end.next) {
end = end.next
half = half.next
if (!end.next)
break
end = end.next
}
return half
}; |
解法:快慢指针解题思路: 快指针一次走两步,慢指针一次走一步,当快指针走到终点时,慢指针刚好走到中间 const middleNode = function(head) {
let fast = head, slow = head
while(fast && fast.next) {
slow = slow.next
fast = fast.next.next
}
return slow
}; 时间复杂度:O(n) 空间复杂度:O(1) |
快慢指针求解很简洁,赞 |
const middle_node = (node1) => {
let fast = node1
let slow = node1
while (fast && fast.next) {
fast = fast.next.next
slow = slow.next
}
return slow
} |
function middleNode (head) { |
var middleNode = function(head) {
// 定义快慢指针
let slow = fast = head;
while(fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}; |
function middleNode(head: ListNode | null): ListNode | null {
let p1 = head
let p2 = head
while(p2 && p2.next) {
p1 = p1.next
p2 = p2.next.next
}
return p1
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给定一个带有头结点
head
的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。
示例 1:
示例 2:
提示:
给定链表的结点数介于 1 和 100 之间。
附leetcode地址:leetcode
The text was updated successfully, but these errors were encountered: