LeetCode-Easy-Merge Two Sorted Lists

###原题目
```cpp
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->4
Output: 1->1->2->3->4->4
```
###拿到手的第一想法
实话说,这道题看到是链表类型的时候,我自己是不会的,因为我的链表基础特别差,连怎么创建一个链表都不知道。所以这道题对我来说实质上是让我好好的学习一下链表吧。
###链表的创建
这会儿重写链表创建,权当复习
```cpp
//结构体链表
 struct ListNode {
     int val;
     ListNode *next;
     ListNode(){};
     ListNode(int x) : val(x), next(NULL) {}
  };
 
  ListNode * creat(ListNode *pfirst){
             ListNode *p=pfirst;//将first的地址赋予p,使用p将pfirst改变,并且p作为移动指针进行移动。
             int n;
             while(cin>>n){
             ListNode *newListNode= new ListNode;
             p-next=newListNode;
             newListNode->val=n;
             newListNode->next=nullptr;
             p=p->next;
             }
             return p;
  }
```
###好的解法
```cpp
class Solution {
public:
 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
  ListNode dummuy(0);
  auto curr = &dummuy;
  while (l1&&l2) {
   if (l1->val <= l2->val) {
    curr->next = l1;
    l1 = l1->next;
   }
   else
   {
    curr->next = l2;
    l2 = l2->next;
   }
   curr = curr->next;
  }
  curr->next = l1 ? l1 : l2;
  return dummuy.next;
 }
};
```
###做题之后的感受
这道题让我再次感受到自己的基础薄弱,特别是在链表这块,基础十分薄弱,后面应该加强复习链表并且不仅需要知道如何创建,也应该知道如何去销毁,如何插入,如何合并。
posted @ 2020-01-01 21:30  Yekko  阅读(129)  评论(0编辑  收藏  举报