标签:style blog class code c java
题目:合并两个有序单链表
思路:一开始想复杂了,以为必须在原链表上修改(绕来绕去还AC了,但是思路相当绕),其实没有,按照正常地合并两个数组同样的方法也对。
代码:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null) return l2; else if(l2 == null) return l1; else{ ListNode p = new ListNode(0); ListNode head = p; while(l1 != null && l2 != null){ if(l1.val <= l2.val){ p.next = l1; l1 = l1.next; }else{ p.next = l2; l2 = l2.next; } p = p.next; } while(l1 != null){ p.next = l1; l1 = l1.next; p = p.next; } while(l2 != null){ p.next = l2; l2 = l2.next; p = p.next; } return head.next; }
}
申请一个新链表头head,逐个将较小的元素链到这个链表头的后面,最后返回head.next就可以啦。
[leetcode]_Merge Two Sorted Lists,布布扣,bubuko.com
[leetcode]_Merge Two Sorted Lists
标签:style blog class code c java
原文地址:http://www.cnblogs.com/glamourousGirl/p/3732317.html