zoukankan      html  css  js  c++  java
  • LeetCode_Merge Two Sorted Lists

    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.
    

      

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(list1 == NULL && list2 == NULL) return NULL;
        	
    		ListNode *head = NULL,  *cur = NULL;
    		while(list1 && list2){	
    			ListNode *tp;
    			if(list1->val >list2->val){
    				tp = list2;
    				list2 = list2->next;
    			}else{
    				tp = list1;
    				list1 = list1->next;
    			}
    			
    			if(cur == NULL){
    				head = cur = tp;
    			}else{
    				cur->next = tp;
    				cur = tp;
    			}
    		}
    		
    		list1 = list1 == NULL ? list2 : list1;
    		if(cur == NULL) 
    				return list1;
    		  else
    				cur->next = list1;
    		
    		return head;	
        }
    };
    

      重写后: 定义一个伪头,省去所有的边界问题。

    /**
     * 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) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(l1 == NULL) return l2;
            if(l2 == NULL) return l1;
            ListNode * head = new ListNode(1);
            ListNode * p = head;
            while(l1 != NULL && l2 != NULL){
            
                if(l1->val < l2->val){
                    p->next = l1;
                    p = l1;
                    l1 = l1->next;
                }else{
                    p->next = l2;
                    p = l2;
                    l2 = l2->next;
                }
            }
            
            p->next = l1 == NULL ? l2 : l1;
            p = head->next;
            delete head;
            
            return p;    
        }
    };
    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    Spring-MVC
    Spring与MyBatis整合(哇,快来看,他写的真好,简单易懂哎)
    Spring事务终极版...
    JdbcTemplate(增删改查以及以注释实现增删改查)
    AOP进阶
    MyBatis增删改查
    JSP的数据交互
    JSP数据交互
    JSP中9大内置对象
    动态网页开发基础
  • 原文地址:https://www.cnblogs.com/graph/p/3039900.html
Copyright © 2011-2022 走看看