合并两个排序链表

来源:互联网 发布:mac 退出vim模式 编辑:程序博客网 时间:2024/04/30 07:15

题目:

将两个排序链表合并为一个新的排序链表

样例

给出 1->3->8->11->15->null2->null, 返回 1->2->3->8->11->15->null

思路:

 首先判断极端情况,即l1=null或l2=null的情况,然后判断两个链表的第一个数谁小,谁小选谁的头结点当head;比如l1的头结点为head,就要对l2进行遍历,让l2当中的元素插入到l1之中即可。

代码:

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param ListNode l1 is the head of the linked list
     * @param ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // write your code here
        if(l1==NULL) 
          return l2;
        if(l2==NULL)
          return l1;
        int i=2;
        if(l1->val<=l2->val)
          {   ListNode *head=l1;
              while(l2!=NULL)
             {
                 while(l1->next->val<l2->val)
                  {if(l1->next==NULL)
                   {  i=1; break;
                   }
                   else l1=l1->next;
                  }
                  if(i==2)
                  {
                  ListNode *T=l1->next;
                  ListNode *Q=l2;
                  l1->next=Q;
                  Q->next=T;
                  l2=l2->next;
                  }
                  else l1->next=l2;
             }
             return head;
          }
        else{
            ListNode *head=l2;
              while(l1!=NULL)
             {
                 while(l2->next->val<l1->val)
                  {if(l2->next==NULL)
                    {i=1;break;
                    }
                   else l2=l2->next;
                  }
                  if(i==2)
                  {ListNode *T=l2->next;
                  ListNode *Q=l1;
                 l2->next=Q;
                 Q->next=T;
                 l1=l1->next;
                  }
                 else l2=l1->next;
             }
             return head;
        }
    }
};

感想:

  做了这道题之后,我最大的感想就是读不清楚题就不要去思考解决方案!我一开始没有注意到链表是已经排序好的,以为这道题是要求两个链表交错之后产生的新链表,结果做了之后,直接错误回答,后来第二天再看这道题的时候,才发现自己犯了一个多么滑稽的错误。个人感觉插入什么的没有难度,这段代码的亮点在于整数i的使用。

0 0
原创粉丝点击