LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*** 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 && l2 == NULL){return NULL;}//如果l1空,l2不空if(l1 == NULL && l2 != NULL){return l2;}//如果l2空,l1不空if(l2 == NULL && l1 != NULL){return l1;}//如果兩個鏈表都不空struct ListNode* l3 = NULL;if(l1 != NULL && l2 != NULL){if(l1->val <= l2->val) {l3 = l1; l1 = l1->next;}else {l3 = l2; l2 = l2->next;}}struct ListNode* end = l3;while(l1 != NULL && l2 != NULL){if(l1->val <= l2->val){end->next = l1;l1 = l1->next;}else{end->next = l2;l2 = l2->next;}end = end->next;}if(l1 == NULL && l2 != NULL){end->next = l2;}if(l2 == NULL && l1 != NULL){end->next = l1;}return l3;}
};void trimLeftTrailingSpaces(string &input) {input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {return !isspace(ch);}));
}void trimRightTrailingSpaces(string &input) {input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {return !isspace(ch);}).base(), input.end());
}vector<int> stringToIntegerVector(string input) {vector<int> output;trimLeftTrailingSpaces(input);trimRightTrailingSpaces(input);input = input.substr(1, input.length() - 2);stringstream ss;ss.str(input);string item;char delim = ',';while (getline(ss, item, delim)) {output.push_back(stoi(item));}return output;
}ListNode* stringToListNode(string input) {// Generate list from the inputvector<int> list = stringToIntegerVector(input);// Now convert that list into linked listListNode* dummyRoot = new ListNode(0);ListNode* ptr = dummyRoot;for(int item : list) {ptr->next = new ListNode(item);ptr = ptr->next;}ptr = dummyRoot->next;delete dummyRoot;return ptr;
}string listNodeToString(ListNode* node) {if (node == nullptr) {return "[]";}string result;while (node) {result += to_string(node->val) + ", ";node = node->next;}return "[" + result.substr(0, result.length() - 2) + "]";
}int main() {string line;while (getline(cin, line)) {ListNode* l1 = stringToListNode(line);getline(cin, line);ListNode* l2 = stringToListNode(line);ListNode* ret = Solution().mergeTwoLists(l1, l2);string out = listNodeToString(ret);cout << out << endl;}return 0;
}
?
總結
以上是生活随笔為你收集整理的LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 螺旋矩阵(Spiral
- 下一篇: LeetCode 20. 有效的括号(V