和大神们学习每天一题(leetcode)-Merge Two Sorted Lists

来源:互联网 发布:java web开发pdf 中文 编辑:程序博客网 时间:2024/06/07 07:08

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.

class Solution {public:ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {if (l2 == NULL)return l1;if (l1 == NULL){l1 = l2;return l1;}ListNode * LNpL1 = l1, *LNpL2 = l2, *LNpFor = NULL;//指针1和2分别指向两个链表的头while (LNpL1 != NULL&&LNpL2 != NULL)//遍历两个链表知道其中一个完全遍历{if (LNpL1->val < LNpL2->val)//比较当前指针指向节点的值,指针1的值如果小于2的值则指针1向后移动{LNpFor = LNpL1;LNpL1 = LNpL1->next;}else//否则将指针2指向的结点插入到指针1指向结点的前面{if (LNpFor == NULL){LNpFor = LNpL2;l1 = LNpFor;}else{LNpFor->next = LNpL2;LNpFor = LNpFor->next;}LNpL2 = LNpL2->next;LNpFor->next = LNpL1;}}if (LNpL1 == NULL)//如果链表1遍历完全,则将链表2剩余结点接在链表1后面{LNpFor->next = LNpL2;}return l1;}};


0 0