算法(17)-单链表-删除指定节点的值-C++

     给定一个单链表head和一个值num,删除链表中值为num的值。
比如1->2->3->4->5->null,num=3 删后即为:1->2->4->5.基本就一coding问题。
思路:用容器将不等于num的节点收集起来再连起来。
           提供两个版本:1.用vector
                                     2.用stack
 1.vector
     

 

//单链表,删除指定值 用容器把不是m_val收集起来然后放在list中
Node* delVal(Node* head, int m_val)
{
	Node* cur = head;
	vector vc;            //变量定义
	int m_temp;
	while (cur != NULL)
	{	
		int m_temp;
		m_temp = cur->m_value;
		if (m_val != m_temp)
		{
			vc.push_back(cur);   //变量赋值
		}
		cur = cur->next;
	}
	int m_size = vc.size();
	cout << "*********************" << endl;
	for (int i = 0; i < m_size; i++)
	{
		cout<<" vc[i] ->m_value="<< vc[i] ->m_value<=0; i--)//vector是从尾巴上加的,注意顺序
	{
		Node* temp = vc[i];            //新节点
		temp->next= np;
		np = temp;
	}
	cout << "*********************" << endl;
	return np;
}


 2.stack
     

Node* delVal(Node* head, int m_val)
{

	Node* cur = head;
	stack st;          //定义
	int m_temp;
	while (cur != NULL)
	{
		int m_temp;
		m_temp = cur->m_value;
		if (m_val != m_temp)
		{
			st.push(cur);     //赋值
		}
		cur = cur->next;
	}
	Node* np = NULL;            //新head
	while (!st.empty())
	{
		 
		Node* temp = st.top();  //取值
		st.pop();               //删除
		temp->next = np;        
		np = temp;
	}
	cout << "*********************" << endl;
	return np;
}

 

你可能感兴趣的:(C++,算法)