单链表中交换元素
Created|Updated
|Post Views:
前言
链表中的交换元素,不同于数组。链表中的操作主要是针对结构中的next

步骤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| void Exchange(Position BeforeP) { Position P, AfterP; P = BeforeP->next; AfterP = P->next;
P->next = AfterP->next; BeforeP->next = AfterP; AfterP->next = P; }
|
示例
单链表1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| #include<stdio.h> #include<stdlib.h> typedef struct Node * PtrToNode; typedef PtrToNode List; typedef PtrToNode Position; void Exchange (Position BeforeP); void PrintList(List L); struct Node { int e; PtrToNode next; };
int main() { List L = NULL; Position prev, current; int n = 0; while (n < 4) { current = (PtrToNode)malloc(sizeof(struct Node)); if(L == NULL) L = current; else prev->next = current; current->next = NULL; current->e = n; prev = current;
n++; } PrintList(L); Exchange(L); PrintList(L);
return 0; }
void Exchange(Position BeforeP) { Position P, AfterP; P = BeforeP->next; AfterP = P->next; P->next = AfterP->next; BeforeP->next = AfterP; AfterP->next = P; }
void PrintList(List L) { while (L != NULL) { printf("%d ", L->e); L = L->next; } printf("\n"); }
|