leetcode测试代码
作者:Lew's Personal Blog 发布于:2019-12-22 22:01 Sunday 分类:Leetcode
- Problem: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.
- Example:
- Input: 1->2->4, 1->3->4
- output: 1->1->2->3->4->4
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) :val(x), next(NULL) {} }; ListNode* mergeTwoList(ListNode* l1, ListNode* l2) { ListNode* newList = new ListNode(0);//头指针位置 ListNode* head = newList; while (l1 != NULL && l2 != NULL) { if (l1->val < l2->val) { head->next = l1; head = head->next; l1 = l1->next;//l1步进 } else { head->next = l2; head = head->next; l2 = l2->next; } } if (l1 == NULL) { head->next = l2; } else { head->next = l1; } return newList->next; } void printListNode(ListNode *l) { while (l->next != NULL) { cout << l->val << "->"; l = l->next; } cout << l->val << endl; } int main(int argc, char **argv) { //l1 ListNode a1(1); ListNode a2(2); ListNode a3(3); ListNode a4(4); a1.next = &a2; a2.next = &a3; a3.next = &a4; a4.next = NULL; //l2 ListNode b1(1); ListNode b2(2); ListNode b3(4); ListNode b4(5); b1.next = &b2; b2.next = &b3; b3.next = &b4; b4.next = NULL; printListNode(&a1); printListNode(&b1); printListNode(mergeTwoList(&a1, &b1)); return 0; }

标签: C++
« 上一篇 单词拆分 | C++沉思录-基础例程 下一篇»