现在的位置: 首页 > 综合 > 正文

Leetcode:merge_two_sorted_lists

2019年11月04日 ⁄ 综合 ⁄ 共 698字 ⁄ 字号 评论关闭

一、     题目

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

二、     分析

   思路很明确,可以分为下面的步骤:

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;
    }
};

抱歉!评论已关闭.