问题
How to merge sorted list l1 and l2 recursively?
回答1:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode result = l1.val > l2.val ? l2 : l1;
ListNode cur = result;
ListNode h1 = result.next;
ListNode h2 = result == l1 ? l2 : l1;
while (h1 != null && h2 != null) {
if (h2.val <= h1.val) {
cur.next = h2;
cur = cur.next;
h2 = h2.next;
} else {
cur.next = h1;
cur = cur.next;
h1 = h1.next;
}
}
while (h1 != null) {
cur.next = h1;
cur = cur.next;
h1 = h1.next;
}
while (h2 != null) {
cur.next = h2;
cur = cur.next;
h2 = h2.next;
}
return result;
}
回答2:
You need a language with call by reference parameters for this problem to make any sense. Even so, you wouldn't want to solve a problem like this recursively. I'd look for another employer.
In C++:
struct Node {
int key;
struct Node *next;
};
void merge(struct Node*& l1, struct Node*& l2) {
// If at the end of l2, we're done.
if (!l2) return;
// If at the end of l1, move all of l2 to l1, then we're done.
if (!l1) {
l1 = l2;
l2 = 0;
return;
}
// If the head of l2 is smaller than the head of l1, pop from l2 and push on l1.
if (l2->key < l1->key) {
// Pop.
Node *l2saved = l2;
l2 = l2saved->next;
// Push.
l2saved->next = l1;
l1 = l2saved;
}
// Recur skipping the node we just merged.
merge(l1->next, l2);
}
For C, just use pointers to pointers instead of references to pointers. Not surprisingly, with optimization turned up clang compiles this to a tight loop.
来源:https://stackoverflow.com/questions/59780599/interview-question-merge-two-sorted-linked-list-without-creating-a-new-list