链表交换节点

链表交换节点

1、普通情况的节点交换流程

2、代码实现

temp_pre->next = p;			//temp的前驱指向p
p_pre->next = p->next;		//p的前驱指向p的后继(记录p的后继)
p->next = temp->next;		//p指向temp的后继
temp->next = p_pre->next;	//temp指向p_pre的后继
p_pre->next = temp;		    //p_pre指向temp

但当两个节点是相邻节点时,上面是操作会发生错误,所以相邻节点单独处理:

	temp->next = p->next;
	p->next = temp;
	temp_pre->next = p;

交换节点的排序:

void sort_dec(book* head)
{
	book* temp_pre=head;
	book* p_pre = head;
	book* ex = NULL;
	//选择排序
	for (book* temp = head->next; temp != NULL; temp = temp->next)
	{
		p_pre = temp;
		for (book* p = temp->next; p != NULL; p = p->next)
		{
			if (temp->price < p->price)
			{
				//下面的修改指针的交换方式
				if (temp->next == p)      //temp与p为相邻结点
				{
					temp->next = p->next;
					p->next = temp;
					temp_pre->next = p;
				}
				else                    //一般情况
				{
					temp_pre->next = p;
					p_pre->next = p->next;//记录p的后继
					p->next = temp->next;
					temp->next = p_pre->next;
					p_pre->next = temp;
				}
				//交换p,temp指针
				ex = temp;
				temp = p;
				p = ex;
			}
			p_pre = p;//循环一次后,p要往后移动,则p的前驱往后移动到原来p的位置
		}
		temp_pre = temp;//循环一次后,temp要往后移动,则temp的前驱往后移动到原来temp的位置
	}
}

posted @ 2022-03-24 13:45  宣哲  阅读(143)  评论(0编辑  收藏  举报