数据结构与算法分析——C语言描述3.3

通过只调整指针(而不是数据)来交换两个相邻的元素

//3.3 a.单链表
void OneListSwapByAdd(ElemType B, ElemType C, List L) {
	Position a_pos, b_pos, c_pos;
	b_pos = Find(B, L);
	c_pos = Find(C, L);
	a_pos = FindPrevious(B, L);
	Position Tmp = (List)malloc(sizeof(Node));
	Tmp->next = a_pos->next;
	a_pos->next = b_pos->next;
	b_pos->next = c_pos->next;
	c_pos->next = Tmp->next;
}

//3.3 b.双链表
void TwoListSwapByAdd(ElemType X1, List L, ElemType X2, List P) {
	List Tmp = (List)malloc(sizeof(Node));
	List a1, b1, a2, b2;
	a1 = FindPrevious(X1, L);
	a2 = FindPrevious(X2, P);
	b1 = Find(X1, L);
	b2 = Find(X2, P);

	Tmp->next = b1->next;
	b1->next = b2->next;
	a2->next = b1;
	b2->next = Tmp->next;
	a1->next = b2;
}

int main()
{
	List L,P;
	ElemType a, b;
	L = CreatedList();
	P = CreatedList();
	PrintList(L);
	PrintList(P);
	printf("请输入需要交换的两个数:");
	scanf_s("%d%d", &a, &b);
	TwoListSwapByAdd(a, L, b, P);
	PrintList(L);
	PrintList(P);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值