亚麻:Insert into a Cyclic Sorted List

这是亚麻的OA题

 

问题描述

Given a node from a cyclic linked list which has been sorted, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node in the list.

 

#include <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vector
#include <unordered_map>
#include <map>
#include <numeric>
#include <list>
#include <numeric>
#include <utility>
//key point
//iterate the lis one time and load all the <value , node*> pair inot mutilmap
//insert a new pair < newval m newnode > into the mutimap;
//construct a cycle list.

//then out the points with Kth distance.
using namespace std;
struct Node {
    int val ;
    Node* next;
    
    Node (int n): val(n){};
};

Node* insertIntoList(Node* pos, int N){
    
    if (pos == nullptr) return new Node(N);
    
    multimap<int , Node*> nodes;
    
    auto cur = pos;
    nodes.insert( make_pair(pos->val,pos));
    pos = pos->next;  // move to the next node.
    
    while ( cur!= pos->next){ // one cycle
        nodes.insert(make_pair(pos->val, pos));
        pos = pos-> next;
    }
    
    // inser the new node into map
    Node* newnode = new Node(N);
    nodes.insert(make_pair(N, newnode));
    
   // construct cycle list from mutimap
    auto itor = nodes.begin();
    auto pre = itor ++;
    while (itor != nodes.end()){
        pre->second->next = itor->second;
        pre++;
        itor ++;
    }
    // pre point to the last node
    pre->second->next = nodes.begin()->second;
    
    return nodes.begin()->second;
}


int main () {
    
    Node* cur = new Node (0);
    Node* temp = cur;
    int cnt =10;
    while (cnt > 0){
        cur -> next = new Node (2*cnt);
        cur = cur->next;
        cnt --;
    }
    cur ->next = temp;
    cout << " the cycle list is created"<< endl;
    
    auto res = insertIntoList(cur, 7);
    //auto res = cur ;
  //  cur = res->next;
    cur = res;
    
    do {
        cout << cur->val <<" " << endl;
        cur = cur-> next ;
        
    } while ( cur != res);

    return 0;
}

 

posted @ 2018-01-14 15:43  HisonSanDiego  阅读(127)  评论(0编辑  收藏  举报