标签:leetcode
Merge Two Sorted 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) { ListNode* T=(ListNode*)malloc(sizeof(ListNode));// 新链表的第一个节点为空节点 ListNode* m; ListNode* n=T; while(l1&&l2){ if(l1->val <= l2->val){ <span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">// 每次比较两条链表的当前节点的值 选择较小的一个加入新的节点</span> m=(ListNode*)malloc(sizeof(ListNode)); m->val=l1->val; m->next=NULL; n->next=m; n=m; l1=l1->next; } else{ m=(ListNode*)malloc(sizeof(ListNode)); m->val=l2->val; m->next=NULL; n->next=m; n=m; l2=l2->next; } } //if(l2||l1){ n->next=l1?l1:l2; <span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">// 把没有遍历完的链表的剩余节点 加入到新链表中 </span> //} return T->next; // 返回空节点的下一个节点 } };
/** * 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* T=(ListNode*)malloc(sizeof(ListNode)); ListNode* m; ListNode* n=T; while(l1&&l2){ if(l1->val <= l2->val){ //m=(ListNode*)malloc(sizeof(ListNode)); //m->val=l1->val; //m->next=NULL; n->next=l1; n=n->next; l1=l1->next; } else{ //m=(ListNode*)malloc(sizeof(ListNode)); //m->val=l2->val; //m->next=NULL; n->next=l2; n=n->next; l2=l2->next; } } //if(l2||l1){ n->next=l1?l1:l2; //} return T->next; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetcode-21-Merge Two Sorted Lists
标签:leetcode
原文地址:http://blog.csdn.net/u014705854/article/details/46732915