链表——(循环和递归)合并两个排序链表
2016-05-09 16:45
453 查看
题目:合并两个递增排序链表,使新链表仍然按照递增排序。
方法一:
基于递归的方法,链表first和链表second各有m和n个结点,新链表的头结点为两个链表中头结点较小
的一个,当找到该头结点时(假设为first的头结点),仍需对first的m-1个结点和second的n个结点合并。
可以看出,子问题和原问题相同,因此可以利用递归解决。
代码如下:
方法二:
基于循环,对两个链表的结点逐个进行比较。
代码如下:
方法一:
基于递归的方法,链表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; } }
相关文章推荐
- hadoop中文教程
- Asianux 3 linux系统下GitLab客户端安装
- 公平锁与非公平锁
- 初探Ajax
- [疯狂Java]NIO:使用Channel、Charset(字符集)、使用Charset传递CharBuffer
- java工程转化为maven工程
- robot API笔记5
- 阶段冲刺7
- 快速优秀
- Html5 上传图片
- Zigbee之旅(一):开天辟地
- 回调
- 路由器桥接(WIFI无线中继)设置及摆放位置图解
- ROS slam gmapping不能画地图
- codeforces 9D DP
- Android微信支付
- AWS EC2
- Java 文件字节字符数据转换
- 187. Repeated DNA Sequences 【M】【30】
- java的多态以及重载,重写,前期绑定,后期绑定