21. Merge Two Sorted Lists

1 題目

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.

2 代碼

/**
 * 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) {
			return l2;
		}
		if (l2 == null) {
			return l1;
		}
		ListNode ls, k, p = l1, q = l2;
		if (p.val > q.val) {
			ls = l2;
			q = q.next;
		} else {
			ls = l1;
			p = p.next;
		}

		k = ls;
		while (p != null && q != null) {
			if (p.val > q.val) {
				k.next = q;
				q = q.next;

			} else {
				k.next = p;
				p = p.next;
			}
			k = k.next;
		}
		if (p != null) {
			k.next = p;
		}
		if (q != null) {
			k.next = q;
		}
		return ls;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章