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.
思路:对两个已排序的单链表合并。算法上比较简单,与归并排序类似。只是数据结构上以前学的,现在忘的比较多,写第一遍的时候比较费力。而且想把重复代码写出方法,但是方法怎么都不能同步改变参数的值,没办法,第一遍力求准确,先A过再说。
代码有点乱,不过理解还是比较方便。如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = null; ListNode p = null; //从小到大的顺序合并链表 while(l1 != null && l2 != null){ if(l1.val > l2.val){ if(head == null){ head = p = l2; }else{ p.next = l2; p = p.next; } l2 = l2.next; }else{ if(head == null){ head = p = l1; }else{ p.next = l1; p = p.next; } l1 = l1.next; } } //如果链表中还有数据,继续合并,以下最多只有一个链表还有数据 while(l1 != null){ if(head == null){ head = p = l1; }else{ p.next = l1; p = p.next; } l1 = l1.next; } while(l2 != null){ if(head == null){ head = p = l2; }else{ p.next = l2; p = p.next; } l2 = l2.next; } p = null; return head; } }
PS:两个代码的效果都差不多。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null || l2 == null) return l1 == null ? l2:l1; ListNode head = new ListNode(0);//定义一个头结点 ListNode p = head; ListNode temp = null; while(l1 != null && l2 != null){ if(l1.val > l2.val){ temp = l2;//用一个temp保存现在的l1或l2 l2 = l2.next;//l1或l2指针后移1位 }else{ temp = l1; l1 = l1.next; }//交换数据 p.next = temp; p = p.next; }//temp取不为空的一个(也可能全为空) temp = l1 == null ?l2:l1; p.next = temp;//将剩余的全部链接即可(上面的方法太啰嗦了) return head.next; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetCode 21.Merge Two Sorted Lists (合并排序链表) 解题思路和方法
原文地址:http://blog.csdn.net/xygy8860/article/details/46778177