資料結構與演算法分析——C語言描述3.3
阿新 • • 發佈:2018-11-03
通過只調整指標(而不是資料)來交換兩個相鄰的元素
//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;
}