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

本文介绍了一种处理嵌套链表的迭代器实现方法,该迭代器能够遍历包含多层级嵌套节点的链表,并按顺序返回所有元素。采用栈结构辅助实现,确保了即使面对复杂的嵌套结构也能正确迭代。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值