#include<stdio.h>
#include<assert.h>
typedef struct _List {
int data;
struct _List* _next;
} List;
void build_link_list(List* l, size_t n) {
List* p = l;
int i = 0;
while (n--) {
++l;
p->data = i++;
p->_next = l;
if (n > 0) p = l;
}
// p is now at the end of the list
p->_next = NULL;
}
void print_link_list(List* listPtr) {
while (listPtr != NULL) {
printf("%d -> ", listPtr->data);
listPtr = listPtr->_next;
}
printf("NULL\n");
}
int swap_list(List **head, List *a, List *b) {
if (a == NULL || b == NULL) return 1;
if (a == b) return 0;
List* prev_a = NULL;
List* prev_b = NULL;
List* tmp = *head;
// find a, b in list; return 2 if not both exist
int found = 0;
if (a == *head) found++;
if (b == *head) found++;
while (tmp->_next != NULL && found != 2) {
if (tmp->_next == a) { prev_a = tmp; found++; }
if (tmp->_next == b) { prev_b = tmp; found++; }
tmp = tmp->_next;
}
if (tmp->_next == NULL && found != 2) return 2;
// update next
if (prev_a != NULL) prev_a->_next = b;
if (prev_b != NULL) prev_b->_next = a;
// swap next
tmp = a->_next;
a->_next = b->_next;
b->_next = tmp;
// update head
if (a == *head) {
*head = b;
} else if (b == *head) {
*head = a;
}
// successfully finished
return 0;
}
int main() {
const size_t SIZE = 7;
List listTest[SIZE];
List* listTestHeadPtr = listTest;
build_link_list(listTest, SIZE);
print_link_list(listTestHeadPtr);
int rtn;
for (size_t i = 0; i < SIZE; i++) {
for (size_t j = i; j < SIZE; j++) {
printf("Swapping %d with %d...\n", (int) i, (int) j);
rtn = swap_list(&listTestHeadPtr, listTest + i, listTest + j);
assert(!rtn);
print_link_list(listTestHeadPtr);
}
}
}