您的位置:首页 > 其它

工具小函数集合

2012-03-15 22:04 183 查看
// 从左边开始,跳过所有无效字符
const char* skip_chars_left(const char* p, const char* chars)
{
	while ( p && *p )
	{
		if ( !strchr(chars, *p) )
		{
			break;
		}
		
		++p;
	}
	
	return p;
}
// 从右边开始,跳过所有无效字符
const char* skip_chars_right(const char* p, const char* chars)
{
	const char* last = p;

	while ( p && *p )
	{
		if ( !strchr(chars, *p) ) // 没有找到过滤字符,则跟随移动
		{
			last = p;
		}
		
		++p;
	}
	
	return (last ? ++last : p); // 往后跳一个字符
}
// 单链表节点数据模型
struct list_node_t
{
	void* data;
	list_node_t* next;
};

// 反转单向链表
list_node_t* reverse_list(list_node_t* head)
{
	list_node_t* p = head;
	list_node_t* q = head;

	head = 0; // 反转后的新链表

	while ( p )
	{
		// 在新链表的头部插入节点p
		q = p->next;
		p->next = head;
		head = p;

		p = q; // p和q指向下一个节点
	}

	return head;
}

// 判断单链表中间是否存在环结构

// 第一种实现:反转链表,判断是否回到头结点
bool find_circle(list_node_t* head)
{
	return (head ? (head == reverse_list(head)) : false);
}

// 第二种实现:快慢指针方法,判断快慢指针是否相遇
bool find_circle(list_node_t* head)
{
	list_node_t* fast = head;
	list_node_t* slow = head;

	while ( fast && fast->next && fast->next->next ) // 快指针到达单链表尾结束
	{
		if ( fast == slow ) // 相遇则存在环
		{
			return true;
		}

		fast = fast->next->next;
		slow = slow->next;
	}

	return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: