C语言:逆置单链表

1.逆置单链表
C语言:逆置单链表_第1张图片

头插法,定义两个指针

ListNode* Reverse(ListNode* p)//不带头结点的链表逆置
{
	if (p == nullptr || p->next == nullptr)//判断是否只有一个节点,若只有一个节点,则不逆置
	{
		return p;
	}
	ListNode* head = (ListNode*)malloc(sizeof(ListNode));
	head->next = nullptr;
	while (p != nullptr)
	{
		ListNode* s = p; 
		p = p->next;
		s->next = head->next;
		head->next = s;
	}
	p = head->next;
	free(head);
	return p;
}
ListNode* Reverse(ListNode* head)//不带头结点的链表逆置(不购买头节点)
{
	if (head == nullptr || head->next == nullptr)
	{
		return head;
	}
	ListNode* p = head->next;
	head->next = nullptr;
	while (p != nullptr)
	{
		ListNode* s = p;
		p = p->next;
		p->next = head;
		head = p;
	}
	return head;
}
ListNode* Reverse(ListNode* head)//头插法逆置
{
	if (head == nullptr || head->next == nullptr) return head;
	ListNode* p = head;
	head = nullptr;
	while (p != nullptr)
	{
		ListNode* s = p;
		p = p->next;
		s->next = head;
		head = s;
	}
	return head;
}

2.重排
C语言:逆置单链表_第2张图片
快慢指针:双指针
3.选择排序
C语言:逆置单链表_第3张图片

void SelectSort(LinkList* plist)//单链表选择排序
{
	assert(plist != nullptr);
	if (plist->head->next == nullptr) return;
	ListNode* p = plist->head->next;//first
	while (p->next != nullptr)
	{
		ListNode* pmin = p;
		ListNode* s = p->next;
		while (s != nullptr)
		{
			if (pmin->data > s->data)
			{
				pmin = s;
			}
			s = s->next;
		}
		if (p != pmin)
		{
			Swap(p->data, pmin->data);
			p = p->next;
		}
	}
}

你可能感兴趣的:(C语言,c语言)