• 合并两个连续的单链表

      1. class Solution {
      2. public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
      3. ListNode temp = new ListNode(0);
      4. ListNode cur = temp;
      5. while(list1 != null && list2 != null) {
      6. if(list1.val > list2.val) {
      7. cur.next = list2;
      8. list2 = list2.next;
      9. } else {
      10. cur.next = list1;
      11. list1 = list1.next;
      12. }
      13. cur = cur.next;
      14. }
      15. cur.next = list2 == null ? list1 : list2;
      16. return temp.next;
      17. }
      18. }
      class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null) {
                return l2;
            } else if (l2 == null) {
                return l1;
            } else if (l1.val < l2.val) {
                l1.next = mergeTwoLists(l1.next, l2);
                return l1;
            } else {
                l2.next = mergeTwoLists(l1, l2.next);
                return l2;
            }
        }
      }
      
    • 删除排序链表中重复元素

      class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode cur = head;
            while(cur != null && cur.next != null) {
                if(cur.val == cur.next.val) {
                    cur.next = cur.next.next;
                } else {
                    cur = cur.next;
                }
            }
            return head;
        }
      }