Given a list which can can contain elements as well as lists, write an iterator to flatten a nested list.
e*a
2 楼
it's not difficult
m*3
3 楼
用c++很难写啊,关键是c++怎么表示一个nested list,有什么好方法么?
b*w
4 楼
type 'a elem = Single of 'a | Multi of ('a elem list);; let rec flatten l = match l with | [] -> [] | hd :: tl -> match hd with | Single x -> x :: flatten tl | Multi x -> (flatten x) @ flatten tl;;
e*2
5 楼
看起来像Ocaml,Haskel之类的。
【在 b*******w 的大作中提到】 : type 'a elem = Single of 'a | Multi of ('a elem list);; : let rec flatten l = : match l with : | [] -> [] : | hd :: tl -> match hd with : | Single x -> x :: flatten tl : | Multi x -> (flatten x) @ flatten tl;;
s*x
6 楼
C++ 怎么表示一个tree node? 用pointer 呗。 用 subclass, pointer to the base class 也可以。
格式都坏了,凑合看吧 这是airbnb的电面题 // [123,456,[788,799,833],[[]],10,[]] // 123->456->788(list)->[](list)->10->(list) // 799 // 833 class nestedList { private: bool isNumber; list l; int val; public: nestedList(string, int&); void print(); }; nestedList::nestedList(string s, int& index) { if(index==s.length()) return; // object is a number if(isdigit(s[index])) { size_t sz; val=stoi(s.substr(index), &sz); // cout << "index==" << index << endl; // cout << "value==" << val << endl; isNumber=true; index+=sz; return; } // object is a list isNumber=false; // s[index]=='[', s[index+1]==']' if(s[index+1]==']') { // list is empty index+=2; return; } // s[index]=='[', s[index+1]==number or '['; do { index++; // skip '[' or ',' nestedList object(s, index); l.push_back(object); } while(s[index]==','); // s[index]==']' index++; // skip ']' return; } void nestedList::print() { // print the number if(isNumber) { cout << val; return; } // print the list cout << '['; for(auto it=l.begin(); it!=l.end(); it++) { it->print(); if(l.end()!=next(it,1)) cout << ','; } cout << ']'; }
【在 t**r 的大作中提到】 : Given a list which can can contain elements as well as lists, write an : iterator to flatten a nested list.
k*g
9 楼
struct Node { int value; struct Node *next; struct Node *nested; }; Node *h = get_list(); if (h->nested) { // then there is a nested list behind this node h = h->nested; } else { // otherwise there is no nested list behind it h = h->next; }