设为首页 加入收藏

TOP

Leetcode:merge_two_sorted_lists
2015-07-20 17:32:29 来源: 作者: 【 】 浏览:2
Tags: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;
    }
};


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Effective C++ 10 下一篇HDU 4786 Fibonacci Tree(生成树..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)