您的位置:首页 > 理论基础 > 数据结构算法

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

2017-12-14 22:33 239 查看
通过只调整指针(而不是数据)来交换两个相邻的元素

//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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息