[LeetCode] 21 - Merge Two Sorted Lists

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.

 

/**
* 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 one is empty, then return another */
    if(l1 == NULL) {
      return l2;
    }
    if(l2 == NULL) {
      return l1;
    }

    ListNode *t1 = l1;
    ListNode *t2 = l2;
    ListNode *tr, *result;
    tr = NULL;
    result = NULL;

    while (t1 || t2) {
      if (t1 == NULL) {
        tr->next = t2;
        break;
      }
      if (t2 == NULL) {
        tr->next = t1;
        break;
      }
      ListNode *tt;
      if (t1->val < t2->val) {
        tt = t1;
        t1 = t1->next;
      } else {
        tt = t2;
        t2 = t2->next;
      }
      if (!result) { // the fisrst time to add a nodel
        tr = tt;
        result = tt;
      } else {
        tr->next = tt;
        tr = tt;
      }
    }
    return result;
  }
};

posted on 2015-08-28 10:54  tuituji  阅读(159)  评论(0编辑  收藏  举报

导航