Skip to content
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

feat: update js solution to lcof problem: No.25 #708

Merged
merged 1 commit into from
Feb 11, 2022
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
66 changes: 40 additions & 26 deletions lcof/面试题25. 合并两个排序的链表/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ class Solution {

### **JavaScript**

- 递归

```js
/**
* Definition for singly-linked list.
Expand All @@ -93,39 +95,51 @@ class Solution {
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
// 法一 - 递归
if (!l1) return l2;
if (!l2) return l1;
if (!(l1 && l2)) {
return l1 || l2;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l2.next, l1);
return l2;
}
// 法二 - 遍历
// if(!l1 || !l2) return l1 ? l1 : l2
// let a = l1
// let b = l2
// let res = l1
// if(a.val > b.val) {
// let c = a
// a = b
// b = c
// res = l2
// }
// while(a && b) {
// while(a.next && a.next.val < b.val) {
// a = a.next
// }
// let tmp = a.next
// let rec = b.next
// a.next = b
// a.next.next = tmp
// a = a.next
// b = rec
// }
// return res
};
```

- 遍历

```js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
const res = new ListNode();
let cur = res;
while (l1 && l2) {
let node;
if (l1.val < l2.val) {
node = l1;
l1 = l1.next;
} else {
node = l2;
l2 = l2.next;
}
cur.next = node;
cur = node;
}
cur.next = l1 || l2;
return res.next;
};
```

Expand Down
29 changes: 3 additions & 26 deletions lcof/面试题25. 合并两个排序的链表/Solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,37 +11,14 @@
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
// 法一 - 递归
if (!l1) return l2;
if (!l2) return l1;
if (!(l1 && l2)) {
return l1 || l2;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l2.next, l1);
return l2;
}
// 法二 - 遍历
// if(!l1 || !l2) return l1 ? l1 : l2
// let a = l1
// let b = l2
// let res = l1
// if(a.val > b.val) {
// let c = a
// a = b
// b = c
// res = l2
// }
// while(a && b) {
// while(a.next && a.next.val < b.val) {
// a = a.next
// }
// let tmp = a.next
// let rec = b.next
// a.next = b
// a.next.next = tmp
// a = a.next
// b = rec
// }
// return res
};