zoukankan      html  css  js  c++  java
  • LeetCode OJ--Merge Two Sorted Lists

    http://oj.leetcode.com/problems/merge-two-sorted-lists/

    有序链表的归并排序

    #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) {
           // default as asend sorted,merge sort
           ListNode *ans = NULL,*ansEnd = NULL,*n1 = l1,*n2 = l2;
           bool firstone = 1;
           while(n1&&n2)
           {
               while(n1->val <= n2 ->val)
               {
                   if(firstone == 1)
                   {
                       ans = ansEnd = n1;
                       //ansEnd = ans->next;
                       firstone = 0;
                       n1 = n1->next;
                   }
                   else
                   {
                       ansEnd->next = n1;
                       ansEnd = n1;
                       n1 = n1->next;
                   }
                   if(n1 == NULL)
                       break;
               }
               if(n1 == NULL)
                   break;
               while(n1->val > n2->val)
               {
                   if(firstone == 1)
                   {
                       ans = ansEnd = n2;
                       firstone = 0;
                       n2 = n2->next;
                   }
                   else
                   {
                       ansEnd->next = n2;
                       ansEnd = n2;
                       n2 = n2->next;
                   }
                   if(n2 == NULL)
                       break;
               }
           }
           if(n1==NULL && n2!= NULL)
           {
               if(firstone ==1)
               {
                   ans = n2;
                   return ans;
               }
               ansEnd->next = n2;
           }
           else if(n2 == NULL && n1 != NULL)
           {
               if(firstone == 1)
               {
                   ans = n1;
                   return ans;
               }
               ansEnd->next = n1;
           }
           return ans;
        }
    };
    
    int main()
    {
        ListNode *n1 = new ListNode(1);
        ListNode *n2 = new ListNode(3);
        ListNode *n3 = new ListNode(5);
    
        n1->next = n2;
    
        Solution myS;
        ListNode *ans = myS.mergeTwoLists(NULL,NULL);
        return 0;
    }
  • 相关阅读:
    人脸识别的一些网站
    41、过滤驱动程序
    13、ActiveX控件
    42、驱动程序调试
    20、宽字符串与字符串间的相互转换
    14、HOOK和数据库访问
    43、Windows驱动程序模型笔记(一)
    7、注册表读写的一个例子
    12、动态链接库,dll
    40、总结IRP,handling IRPs,Part II
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3524865.html
Copyright © 2011-2022 走看看