Well, this is too easy. I think this can be solved very quickly. My answer is shown as below:
/**
* 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 tmp1 = l1;
ListNode tmp2 = l2;
ListNode newHead = null;
ListNode movingNode = null;
while(tmp1!= null && tmp2!=null){
if(tmp1.val <= tmp2.val){
if(newHead == null){
newHead = tmp1;
movingNode = newHead;
}
else {
movingNode.next = tmp1;
movingNode = movingNode.next;
}
tmp1 = tmp1.next;
}
else{
if(newHead == null){
newHead = tmp2;
movingNode = newHead;
}
else {
movingNode.next = tmp2;
movingNode = movingNode.next;
}
tmp2 = tmp2.next;
}
}
if(tmp1 == null && tmp2 != null) movingNode.next = tmp2;
else if(tmp2 == null && tmp1 != null)movingNode.next = tmp1;
return newHead;
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
No comments:
Post a Comment