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.
if... else if不要偷懒直接写 if...if...
/** * 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) { ListNode *head = NULL,*temp = head; if(l1 == NULL && l2 == NULL)return NULL; if(l1 == NULL && l2 != NULL)return l2; if(l1 != NULL && l2 == NULL)return l1; while(l1 != NULL && l2 != NULL) { if(l1->val <= l2->val) { if(head == NULL) { head = l1; temp = head; l1 = l1->next; continue; } temp->next = l1; l1 = l1->next; temp = temp->next; } else if(l1->val > l2->val) { if(head == NULL) { head = l2; temp = head; l2 = l2->next; continue; } temp->next = l2; l2 = l2->next; temp = temp->next; } } if(l1 == NULL)temp ->next = l2; else if(l2 == NULL) temp ->next =l1; return head; } };
posted on 2014-02-27 21:28 pengyu2003 阅读(81) 评论(0) 编辑 收藏 举报