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.
思想和merge sort一样,只是要考虑相等的情况的时候该怎么办。
/** * 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 result = new ListNode(0); ListNode returnResult = result; while (l1 != null && l2 != null) { while (l1 != null && l2 != null && l1.val < l2.val) { result.next = l1; l1 = l1.next; result = result.next; } while (l1 != null && l2 != null && l1.val > l2.val) { result.next = l2; l2 = l2.next; result = result.next; } while (l1 != null && l2 != null && l1.val == l2.val) { result.next = l1; l1 = l1.next; result = result.next; result.next = l2; l2 = l2.next; result = result.next; } } if (l1 == null) { result.next = l2; } else { result.next = l1; } return returnResult.next; }}
写的还是有些冗余了。。。
简洁版:
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } ListNode result = new ListNode(0); ListNode returnResult = result; while (l1 != null && l2 != null) { if (l1.val < l2.val) { result.next = l1; l1 = l1.next; } else { result.next = l2; l2 = l2.next; } result = result.next; } if (l1 == null) { result.next = l2; } else { result.next = l1; } return returnResult.next; }}
没想到还可以用recursion做
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } ListNode result = null; if (l1.val < l2.val) { result = l1; result.next = mergeTwoLists(l1.next, l2); } else { result = l2; result.next = mergeTwoLists(l1, l2.next); } return result; }}
时隔两个月再来做这道题,发现自己还是进步了的~至少直接写出了简洁版。吼吼吼
也又写了一遍recursion
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } if (l1.val > l2.val) { l2.next = mergeTwoLists(l1, l2.next); return l2; } else { l1.next = mergeTwoLists(l1.next, l2); return l1; } }}
C++版本:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) { return l2; } if (l2 == NULL) { return l1; } if (l1 -> val > l2 -> val) { l2 -> next = mergeTwoLists(l1, l2 -> next); return l2; } else { l1 -> next = mergeTwoLists(l1 -> next, l2); return l1; } }};
c++另一种写法怎么也写不过。。。不懂指针什么的,到时候懂了再来写吧。。。#未完待续#需回顾。。。