您的位置:首页 > 其它

LeetCode OJ算法题(六十四):Merge Two Sorted Lists

2014-08-26 21:51 176 查看
题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first
two lists.

解法:

实际上就是归并排序的链表实现。

一趟合并中,不再需要重新创建一个数组来保存合并的结果,因为这里是链表实现,因此,用p指向已经合并好的链表的尾部,l1指向第一张链表下一个应该比较的节点,l2指向第二个链表的下一个应该比较的节点。

接下来需要分开讨论:

如果l1<l2(这里省略了取val的操作),且p指向的是l1,中的节点(用p.next 与 l1比较可知),那么直接p=p.next;

如果l1<l2,且p指向l2的前一个节点,那么需要把p的next指向l2,然后l2后移,p后移

当l2<l1时操作类似。

最后当某一个链表遍历完后,把另一链表剩下的部分连接上去即可

public class No64_MergeTwoSortedLists {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static void main(String[] args){
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(7);
ListNode n3 = new ListNode(8);
ListNode n4 = new ListNode(2);
ListNode n5 = new ListNode(4);
ListNode n6 = new ListNode(6);
// n1.next = n2;
// n2.next = n3;
n4.next = n5;
n5.next = n6;
ListNode head = mergeTwoLists(n1, n4);
while(head != null){
System.out.println(head.val+" ");
head = head.next;
}

}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode head;
if(l1.val < l2.val){
head = l1;
l1 = l1.next;
}
else{
head = l2;
l2 = l2.next;
}
ListNode p = head;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
if(p.next != l1) p.next = l1;
p = p.next;
l1 = l1.next;
}
else{
if(p.next != l2) p.next = l2;
p = p.next;
l2 = l2.next;
}
}
if(l1 == null) p.next = l2;
if(l2 == null) p.next = l1;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 链表