C++单链表中删除指定范围内的元素

//删除指定范围内的所有元素
template
void chain::removeRange(int fromIndex, int toIndex)
{
	  chainNode*deleteNode;
	  chainNode*p = firstNode;
	  if (fromIndex == 0)                                //方法复杂度O(toIndex-fromIndex+1)
	  {                                                   //思想是如果首位是0号元素,则先删除0后面的元素,最后把0号元素删除
		  for (int i = 0; i < toIndex - fromIndex; i++)
		  {
			  deleteNode = p->next;
			  p->next = p->next->next;
			  delete deleteNode;
			  listSize--;
		  }
		  deleteNode = firstNode;
		  firstNode = firstNode->next;
		  delete deleteNode;
		  listSize--;
	  }
	  else                                             //如果是非0开始,则先找到起始元素的前驱,再逐个删除
	  {
		  for (int i = 0; i < fromIndex - 1;i++)
			  p = p->next;
		  for (int i = 0; i < toIndex - fromIndex + 1;i++)
		  {
			  deleteNode = p->next;
			  p->next = p->next->next;
			  delete deleteNode;
			  listSize--;
		  }
	  }
	}

你可能感兴趣的:(数据结构)