leetcode Merge Two Sorted Lists 통합 두 개의 정렬 체인 테이블
4832 단어 leetcode
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else {
l2->next = mergeTwoLists(l2->next, l2);
return l2;
}
}
}; 2. 비귀속
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode *temphead = NULL;
ListNode *l1pointer = l1;
ListNode *l2pointer = l2;
ListNode *temptail = NULL;
// , l1,l2 ,
if (l1->val < l2->val) {
temphead = l1;
l1pointer = l1pointer->next;
}
else {
temphead = l2;
l2pointer = l2pointer->next;
}
temptail = temphead;
while (l1pointer != NULL && l2pointer != NULL) {
// l1,l2
if (l1pointer->val < l2pointer->val){
temptail->next = l1pointer;
l1pointer = l1pointer->next;
}
else {
temptail->next = l2pointer;
l2pointer = l2pointer->next;
}
temptail = temptail->next;
}
if (l1pointer == NULL)
temptail->next = l2pointer;
else
temptail->next = l1pointer;
return temphead;
}
}; 귀속 방법은 비용이 많이 들고, 체인 시계가 너무 길면 넘칠 수 있으니, 비귀속 방법을 추천합니다.