Merge Two Sorted Lists
2015-02-12 15:18
357 查看
/** * 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 l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; ListNode pointer = new ListNode(0); ListNode answer = pointer; int i = 0; while(l1 != null || l2 != null) { if(l1 == null) { pointer.next = l2; pointer = pointer.next; l2 = l2.next; } else if(l2 == null) { pointer.next = l1; pointer = pointer.next; l1 = l1.next; } else if(l1.val <= l2.val ) { pointer.next = l1; pointer = pointer.next; l1 = l1.next; } else if(l1.val > l2.val ) { pointer.next = l2; pointer = pointer.next; l2 = l2.next; } } return answer.next; } }
上面这个是自己的solution,下面的是leetcode上别人的solution。
ListNode pointer = new ListNode(0);//ListNode pointer = new ListNode();
ListNode answer = pointer;//ListNode answer =pointer;
有一点不明白就是上面片段的语句按照注释里写怎么就不对了,求大神教学啊!ListNode(0)是初始化 pointer为{ 0 }么?
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode headcopy = head;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
headcopy.next = l1;
l1 = l1.next;
}
else if(l2.val <= l1.val){
headcopy.next = l2;
l2 = l2.next;
}
headcopy = headcopy.next;
}
headcopy.next = (l1 == null ? l2 : l1);
return head.next;
}
}
相关文章推荐
- [Leetcode] Merge Two Sorted Lists
- Merge Two Sorted Lists
- leetcode-21 Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- Merge Two & k Sorted Lists & Merge Sorted Array
- LeetCode-Merge Two Sorted Lists
- leetcode:21 Merge Two Sorted Lists-每日编程第十七题
- Merge Two Sorted Lists
- <LeetCode OJ> 21. Merge Two Sorted Lists
- 【LeetCode OJ】Merge Two Sorted Lists
- 【leetcode】Merge Two Sorted Lists
- leetcode第一刷_Merge Two Sorted Lists
- LeetCode(21)——Merge Two Sorted Lists
- Merge Two Sorted Lists
- 编程题2- Merge Two Sorted Lists(leetcode-21)
- LeetCode:Merge Two Sorted Lists
- leetcode Merge Two Sorted Lists(Java)
- Leetcode 21 Merge Two Sorted Lists
- Leetcode 21 - Merge Two Sorted Lists
- Merge Two Sorted Lists-python