Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

add JS solution for 0141 0160 #166

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

Merged
merged 1 commit into from
Apr 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions solution/0141.Linked List Cycle/Solution2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
var hasCycle2 = function(head) {
let slow = head
let fast = head
while (fast !== null && fast.next !== null) {
slow = slow.next
fast = fast.next.next
if (slow === fast) {
return true
}
}
return false
}

var hasCycle3 = function(head) {
let arr = []
while (head !== null) {
if (arr.includes(head)) {
return true
}
arr.push(head)
head = head.next
}
return false
}
45 changes: 45 additions & 0 deletions solution/0160.Intersection of Two Linked Lists/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
var getIntersectionNode2 = function(headA, headB) {
if (!headA || !headB) {
return null
}
let q = headA, p = headB
let lengthA = 1
let lengthB = 1
while(q.next) {
q = q.next
lengthA++
}
while (p.next) {
p = p.next
lengthB++
}
if (q !== p) {
return null
}

q = headA, p = headB
if (lengthA > lengthB) {
for (let i = 0; i < lengthA - lengthB; i++) {
q = q.next
}
} else {
for (let i = 0; i < lengthB - lengthA; i++) {
p = p.next
}
}
while (q !== p && q !== null) {
q = q.next
p = p.next
}
return q
};

var getIntersectionNode = function(headA, headB) {
let p1 = headA;
let p2 = headB;
while (p1 != p2) {
p1 = p1 ? p1.next : headB;
p2 = p2 ? p2.next : headA;
}
return p1;
}