Leetcode21. Merge Two Sorted Lists

来源:互联网 发布:友情链接交易平台源码 编辑:程序博客网 时间:2024/06/05 16:49

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.

Example:

Input: 1->2->4, 1->3->4Output: 1->1->2->3->4->4
这题断断续续刷了好久,好讨厌coding被人打断,忧桑...
其实还挺简单的一道链表合并。
#include<iostream>using namespace std; struct ListNode {     int val;     ListNode *next;     ListNode(int x) : val(x), next(NULL) {} };class Solution {public:ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {ListNode* head = NULL;if (l1 == NULL&&l2 == NULL)return 0;else if (l1 == NULL&&l2 != NULL)return l1;else if (l1 != NULL&&l2 == NULL)return l2;ListNode* p = l1;ListNode* q = l2;ListNode* tail = NULL;if (p->val <= q->val){head = p;p = p->next;}else{head = q;q = q->next;}tail = head;while (p != NULL&&q != NULL){if (p->val <= q->val){tail->next = p;p = p->next;}else{tail->next = q;q = q->next;}tail = tail->next;}if (p != NULL)tail->next = p;elsetail->next = q;return head;}};int main(){ListNode* a = new ListNode(1);ListNode* b = new ListNode(2);ListNode* c = new ListNode(3);ListNode* d = new ListNode(1);ListNode* e = new ListNode(3);ListNode* f = new ListNode(4);a = NULL;d = NULL;/*a->next = b;b->next = c;c->next = NULL;d->next = e;e->next = f;f->next = NULL;*/Solution s;ListNode* head;head = s.mergeTwoLists(a, d);while (head != NULL){cout << head->val;head = head->next;}}

原创粉丝点击