zoukankan      html  css  js  c++  java
  • Leetcode:merge_two_sorted_lists

    一、     题目

       合并两个排好序的链表。依照节点的大小排列。

    二、     分析

       思路非常明白。能够分为以下的步骤:

    1.     假设当中一个为NULL,则返回另外一个链表就可以

    2.     推断两个链表节点的大小。选取小的接入目标链表,并同一时候把链表后移

    3.     当至少有一个链表为NULL时。则推断是哪一个为空,并将还有一个链表接入目标链表就可以

    注意:过程中因为初始时将目标链表置NULL,导致WA了好多次。这里我最后返回的是next

     

    /**
     * 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) {
        	ListNode *Listtar,*head;
        	//Listtar=NULL;
        	head=Listtar;
        	if(l1==NULL)
        	   return l2;
        	if(l2==NULL)
        	   return l1; 
    		     
        	while(l1&&l2){
        		if(l1->val>l2->val){
        			Listtar->next=l2;
        			l2=l2->next;
        			Listtar=Listtar->next;
        		}
        		else {
        			Listtar->next=l1;
        			l1=l1->next;
        			Listtar=Listtar->next;
        		}
        	}
            if(l1)
            	Listtar->next=l1;
            else
            	Listtar->next=l2;
            	
            return head->next;
        }
    };


  • 相关阅读:
    精算师的前世今生
    失落的C语言结构体封装艺术
    关于联合的一些介绍
    变量的声明和定义
    C/C++内存分配区
    探寻周瑜“前世今生”
    SpringBoot中使用AOP
    springBoot中的事物管理
    springBoot整合多数据源
    spingBoot整合mybatis+generator+pageHelper
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6832711.html
Copyright © 2011-2022 走看看