Skip to main content

4 posts tagged with "linkedList"

View All Tags

· One min read

https://leetcode.com/problems/linked-list-cycle/

Solution 1

/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/

/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
if (head === null) {
return false;
}

let curr = head;
let next = head.next;

while (next && next.next) {
curr = curr.next;
next = next.next.next;

if (curr === next) {
return true;
}
}

return false;
};

· One min read

https://leetcode.com/problems/intersection-of-two-linked-lists/

Solution 1

/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/

/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function (headA, headB) {
if (!headA || !headB) {
return null;
}

let nodeA = headA;
let nodeB = headB;

while (nodeA !== nodeB) {
nodeA = nodeA.next;
nodeB = nodeB.next;

console.log(nodeA, nodeB);

if (nodeA === nodeB) {
return nodeA;
}

if (!nodeA) {
nodeA = headB;
}
if (!nodeB) {
nodeB = headA;
}
}

return nodeA;
};

· One min read

https://leetcode.com/problems/merge-two-sorted-lists/

Solution 1

/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
let merge = new ListNode();
let head = merge;

while (l1 && l2) {
if (l1.val < l2.val) {
merge.next = l1;
l1 = l1.next;
} else {
merge.next = l2;
l2 = l2.next;
}
merge = merge.next;
}

if (!l1) merge.next = l2;
else if (!l2) merge.next = l1;

return head.next;
};

Runtime: 89 ms

Memory Usage: 44.4 MB

· One min read

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Solution 1

/**
* 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 {ListNode}
*/
var deleteDuplicates = function (head) {
if (!head) {
return null;
}

let curr = head;
let next = head.next;

while (next) {
if (curr.val === next.val) {
curr.next = next.next;
} else {
curr = curr.next;
}
next = next.next;
}

return head;
};