题目要求: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 (l1 == NULL && l2 == NULL) return NULL; else if (l1 == NULL && l2 != NULL) return l2; else if (l1 != NULL && l2 == NULL) return l1; ListNode* l = NULL; ListNode* head = NULL; if (l1->val < l2->val) { l = l1; l1 = l1->next; } else { l = l2; l2 = l2->next; } head = l; while (l1 != NULL && l2 != NULL) { if (l1->val < l2->val) { l->next = l1; l1 = l1->next; l = l->next; } else { l->next = l2; l2 = l2->next; l = l->next; } } if (l1 != NULL) l->next = l1; else if (l2 != NULL) l->next = l2; return head; } };
Leetcode (2) Merge Two Sorted Lists
原文地址:http://blog.csdn.net/angelazy/article/details/44995369