标签:
首先两个单链表是有序的
在融合两个单链表的时候,如果想到的是在一个序列上进行增减,那么会非常麻烦
这里一定要单独开一个序列头进行存储,不一定需要开辟内存,主要是一个概念
其实方法感觉和归并算法的merge都是一个概念
/** * 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) { return l2; } else if(l2 == NULL) { return l1; } ListNode *head = NULL; if(l1->val < l2->val) { head = l1; l1 = l1->next; } else { head = l2; l2 = l2->next; } ListNode *phead = head; while(l1 && l2) { if(l1->val < l2->val) { head->next = l1; head = head->next; l1 = l1->next; } else { head->next = l2; head = head->next; l2 = l2->next; } } if(l1) { head->next = l1; } if(l2) { head->next = l2; } return phead; } };
/** * 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) { return l2; } else if(l2 == NULL) { return l1; } ListNode *head = NULL; if(l1->val < l2->val) { head = l1; head->next = mergeTwoLists(l1->next,l2); } else { head = l2; head->next = mergeTwoLists(l1,l2->next); } return head; } };
LeetCode—Merge Two Sorted Lists融合两个有序单链表
标签:
原文地址:http://blog.csdn.net/xietingcandice/article/details/45059819