首页 > 代码库 > [LeetCode]21 Merge Two Sorted Lists
[LeetCode]21 Merge Two Sorted Lists
https://oj.leetcode.com/problems/merge-two-sorted-lists/
http://blog.csdn.net/linhuanmars/article/details/19712593
/** * 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 && l2 == null) return null; ListNode toReturn = null; ListNode curNode = null; ListNode lastNode = null; while (l1 != null || l2 != null) { // Select current node; if (l1 == null) { curNode = l2; l2 = l2.next; } else if (l2 == null) { curNode = l1; l1 = l1.next; } else if (l1.val < l2.val) { curNode = l1; l1 = l1.next; } else { curNode = l2; l2 = l2.next; } if (toReturn == null) toReturn = curNode; if (lastNode != null) lastNode.next = curNode; lastNode = curNode; } return toReturn; } }
[LeetCode]21 Merge Two Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。