CareerCup Program an iterator for a Linked List which may include nodes which are nested within othe

来源:互联网 发布:中网络电视台 编辑:程序博客网 时间:2024/05/17 09:11

Program an iterator for a Linked List which may include nodes which are nested within other nodes. i.e. (1)->(2)->(3(4))->((5)(6). Iterator returns 1->2->3->4->5->6

-------------------------------------------------------------


C++ solution. This one also uses a stack, similar to previous answers 
I omitted some code which is not relevant to the question itself, as well as some "friend" commands to make it more readable. 

NestedNode contains a value and two pointers: to the nested element and to the next element.

template <class C>class NestedNode{public:NestedNode(C value, NestedNode<C> *pNested = NULL) : m_value(value), m_pNested(pNested), m_pNext(NULL) {}C value() const { return m_value; }protected:C m_value;NestedNode<C> *m_pNested;NestedNode<C> *m_pNext;};

NestedList is a simple list containing head and tail pointers:

template <class C>class NestedList{public:NestedList() : m_pHead(NULL), m_pLast(NULL) {}NestedNode<C> *head() { return m_pHead; }void push_back(NestedNode<C> *pNode) { /* omitted */ }protected:NestedNode<C> *m_pHead;NestedNode<C> *m_pLast;};

Here is the iterator.

template <class C>class NestedIter {public:NestedIter(NestedNode<C> *pNode){m_stack.push(pNode);}NestedNode<C> *next(){if (m_stack.size() == 0)return NULL;NestedNode<C> *pCur = m_stack.top();m_stack.pop();if (pCur->m_pNext)m_stack.push(pCur->m_pNext);if (pCur->m_pNested)m_stack.push(pCur->m_pNested);return pCur;}protected:stack<NestedNode<C> *> m_stack;};

And a sample "main"

int main(){NestedList<int> aList;aList.push_back(new NestedNode<int>(1) );aList.push_back(new NestedNode<int>(2) );aList.push_back(new NestedNode<int>(3, new NestedNode<int>(4) ));aList.push_back(new NestedNode<int>(5, new NestedNode<int>(6) ));NestedIter<int> nestedIter(aList.head());NestedNode<int> *pNode;while ((pNode = nestedIter.next()) != NULL) cout << pNode->value() << " -> ";cout << "|" << endl;}

0 0
原创粉丝点击