复杂的链表的深度拷贝LeetCode138
深度拷贝后的链表和原链表完全独立
map的应用
#include <studio.h>
#include < map>
struct RandomListNode{
int label;
RandomListNode * next,* random;
RandomListNode(int x):label(x),next(NULL),random(NULL){}
};
int main(){
std::map<RandomListNode *,int >node_map;
RandomListNode a(5);
RandomListNode b(3);
RandomListNode c(6);
a.next=&b;
b.next=&c;
a.random=&c;
b.random=&a;
c.random=&c;
node_map[&a]=1;
node_map[&b]=2;
node_map[&c]=3;
printf("a.random id=%d\n",node_map[a.random]);
printf("b.random id=%d\n",node_map[b.random]);
printf("c.random id=%d\n",node_map[c.random]);
return 0;
}
思路:节点地址与节点序号对应
RandomListNode * copyRandomList(RandomListNode * head){
std::map<RandomListNode *, int> node_map;
std::vector<RandomListNode *> node_vec;
RandomListNode * ptr=head;
int i=0;
while(ptr){
node_vec.push_back(new RandomListNode(ptr->label));
node_map(ptr)=i;##记录原始链表地址到节点位置的映射
ptr=ptr->next;
i++;
}
node_vec.push_back(0);
prt=head;
i=0;
while(ptr){
node_vec[i]->next=node_vec[i+1];
if(ptr->random){
int id=node_map[ptr->random];
node_vec[i]->random=node_vec[id];
}
ptr=ptr->next;
i++;
}
return node_vec[0];
}
排序链表的合并LeetCode21
ListNode * mergeTwoLists(ListNode * l,ListNode *s){
ListNode temp_head(0);##临时头节点
ListNode *pre=&temp_head;##指向该节点
while(l && s){
if(l->val>s->val){
pre->next=s;
s=s->next;
}
else{
pre->next=s;
s=s->next;
}
}
if(l){
pre->next=l;
l=l->next;
}
if(s){
pre->next=s;
s=s->next;
}
return temp_head.next;
}
排序K个链表的合并LeetCode23
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
bool cmp(const ListNode *a,const ListNode *b){
return a->val < b->val;
}
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
std::vector<ListNode *>node_vec;
for(int i=0;i<lists.size();i++){
ListNode *head=lists[i];
while(head){
node_vec.push_back(head);
head=head->next;
}
}
if (node_vec.size()==0){
return NULL;
}
std::sort(node_vec.begin(),node_vec.end(),cmp);
for(int i=1;i<node_vec.size();i++){
node_vec[i-1]->next=node_vec[i];
}
node_vec[node_vec.size()-1]->next=NULL;
return node_vec[0];
}
};
用递归方法:
ListNode *mergeKLists(std::vector<ListNode *>&lists){
if(lists.size()==0)return NULL;
if(lists.size()==1)return lists[0];
if(lists.size()==2){
return mergeTwoLists(lists[0],lists[1]);
}
int mid=lists.size()/2;
std::vector<ListNode *>sub1_lists;
std::vector<ListNode *>sub2_lists;
for(int i=0;i<mid;i++){
sub1_lists.push_back(lists[i]);
}
for(int i=mid;i<lists.size();i++){
sub2_lists.push_back(lists[i]);
}
ListNode*l1=mergeKlists(sub1_lists)
ListNode*l2=mergeKlists(sub2_lists)
return mergeTwoLists(l1,l2);
}