1. 程式人生 > >LeetCodet題解--21. Merge Two Sorted Lists(合併兩個排序好的連結串列)

LeetCodet題解--21. Merge Two Sorted Lists(合併兩個排序好的連結串列)

連結

題意

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

>

Subscribe to see which companies asked this question

合併兩個排序好的連結串列

分析

簡單題,只要對兩個連結串列中的元素進行比較,然後移動即可,只要對連結串列的增刪操作熟悉,幾分鐘就可以寫出來,程式碼如下:
·

#include <iostream>

using namespace std;

#define __tmain main



#ifdef __tmain
struct ListNode
{
public :
    int val;
    ListNode *next;
    //ListNode(int x) : val(x), next(NULL) {}
};
#endif // __tmain

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution { public: ListNode* mergeTwoLists(ListNode* left, ListNode* right) { if(left == NULL && right == NULL) // 兩個連結串列均為空 { return NULL; } else if(left != NULL && right == NULL) // left不為空, right為空 { return
left; } else if(left == NULL && right != NULL) // left為空, right不為空 { return right; } // 先生成頭結點 ListNode *head = NULL; if(left->val < right->val) { head = left; left = left->next; //cout <<left->val <<"in list" <<endl; } else { head = right; right = right->next; //cout <<right->val <<"in list" <<endl; } // 遍歷兩個連結串列 ListNode *curr = head; while(left != NULL && right != NULL) { // 每次找到一個小的加入新的連結串列 //cout <<"left = " <<left->val <<", right = " <<right->val <<endl; if(left->val < right->val) { //cout <<left->val <<"in list" <<endl; curr->next = left; curr = curr->next; left = left->next; } else { //cout <<right->val <<"in list" <<endl; curr->next = right; curr = curr->next; right = right->next; } } // 處理較長連結串列的剩餘部分 if(left != NULL) { curr->next = left; } else { curr->next = right; } return head; } }; int __tmain( ) { ListNode left, right[3]; left.val = 5; left.next = NULL; right[0].val = 1; right[0].next = &right[1]; right[1].val = 2; right[1].next = &right[2]; right[2].val = 4; right[2].next = NULL; Solution solu; ListNode *head = solu.mergeTwoLists(&left, right); while(head != NULL) { cout <<head->val; head = head->next; } }