题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
解题思路(迭代):
先定义两个指针,一个指针不负责移动是指向头结点的指针,第二个指针负责移动,将数据挨个串在一起
public ListNode MergeTwoLists1(ListNode list1, ListNode list2)
{
//定义一个返回的指针和不动的指针
ListNode res = new ListNode(0);
ListNode cur = res;
//如果list1和list2的下一个指向的不是null
while (list1 != null && list2 != null)
{
if (list1.val <= list2.val)
{
cur.next = list1;
cur = cur.next;
list1 = list1.next;
}
else
{
cur.next = list2;
cur = cur.next;
list2 = list2.next;
}
}
//如果一个链表为空了,就可以把另外一个不为空的链表直接接在后面
if (list1 != null)
cur.next = list1;
if (list2 != null)
cur.next = list2;
return res.next;
}
解题思路(递归):
利用递归的特性,每一次都返回当前两个链表的最大的值再将他们链接在一起
public ListNode MergeTwoLists2(ListNode list1, ListNode list2)
{
//递归的返回条件
if (list1 == null)
return list2;
if (list2 == null)
return list1;
//每次递归返回的都是最大的value,可以理解返回最大的val后将链表的指针向后移动传入进函数中
if(list1.val <= list2.val)
{
//返回来之后再进行拼接
list1.next = MergeTwoLists2(list1.next, list2);
return list1;
}
else
{
list2.next = MergeTwoLists2(list1, list2.next);
return list2;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)