Leetcode刷题——day6

腾讯50题之合并两个有序链表

  • 前言
  • 一、题目要求
  • 二、题解方法(c语言)
    • 1.法一:递归法
    • 2.常规写法(适合数据结构初学)
  • 总结


前言


过程即奖励

一、题目要求

将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
Leetcode刷题——day6_第1张图片
示例:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

二、题解方法(c语言)

1.法一:递归法

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
    if(l1==NULL)return l2;
    if(l2==NULL)return l1;
    if(l1->val<l2->val){
        l1->next=mergeTwoLists(l1->next,l2);//求出一个小的都要将去掉这个小的l1和整l2作比较
        return l1;
    }
    else{
        l2->next=mergeTwoLists(l2->next,l1);
        return l2;
	}
}

2.常规写法(适合数据结构初学)

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if (!l1)
		return l2;
	if (!l2)
		return l1;
	struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)), *t = head;
	while (l1 && l2){
		if (l1->val < l2->val){
			t->next = l1;
			l1 = l1->next;
		}			
		else{
			t->next = l2;
			l2 = l2->next;
		}			
		t = t->next;		
	}
	if (l1)      t->next = l1;
	else if (l2) t->next = l2;
	return head->next;
}

总结

Stay hungry. Stay foolish.

你可能感兴趣的:(leetcode刷题,数据结构,leetcode,算法,链表)