您的位置:首页 > 其它

链表——(循环和递归)合并两个排序链表

2016-05-09 16:45 453 查看
题目:合并两个递增排序链表,使新链表仍然按照递增排序。

方法一:

基于递归的方法,链表first和链表second各有m和n个结点,新链表的头结点为两个链表中头结点较小

的一个,当找到该头结点时(假设为first的头结点),仍需对first的m-1个结点和second的n个结点合并。

可以看出,子问题和原问题相同,因此可以利用递归解决。

代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode first, ListNode second) {

if(first==null)
return second;
if(second==null)
return first;

ListNode head=null;

if(first.val<second.val)
{
head=first;
head.next=mergeTwoLists(first.next,second);
}else
{
head=second;
head.next=mergeTwoLists(first,second.next);
}
return head;
}
}


方法二:

基于循环,对两个链表的结点逐个进行比较。

代码如下:

public class Solution {
public ListNode mergeTwoLists(ListNode first, ListNode second) {
if(first==null)
return second;
if(second==null)
return first;

ListNode head=null;
ListNode temp=null;
ListNode cur =null;

//当first和second都没有到各自链表的结尾;
while(first!=null&&second!=null)
{
if(first.val<second.val)
{
temp=first;
first=first.next;
}else
{
temp=second;
second=second.next;
}

if(head==null)
{
head=temp;
cur=temp;
}else
{
cur.next=temp;
cur=temp;
}
}
//first和second中的一个到链表的结尾;
if(first!=null)
{
cur.next=first;
}else
{
cur.next=second;
}

return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: