链表常见操作有:
- 链表逆序
- 链表每相邻两个元素逆序,例如 1, 2, 3, 4 => 2, 1, 4, 3
- 探测是否构成环路
#include <stdio.h>
#include <stdlib.h>
typedef struct NodeStruct {
int data;
struct NodeStruct *next;
} Node, *Position, *List;
void initList(List *l) {
*l = malloc(sizeof(Node));
(*l)->next = NULL;
}
void insertList(List l, int v) {
Position tmp = malloc(sizeof(Node));
Position cur = l;
tmp->data = v;
tmp->next = NULL;
while(cur->next != NULL) {
cur = cur->next;
}
cur->next = tmp;
}
void printList(List l) {
Position cur = l->next;
printf("\nlist begin\n");
while(cur != NULL) {
printf("%4d", cur->data);
cur = cur->next;
}
printf("\nlist end\n");
}
// 1, 2, 3, 4 => 4, 3, 2, 1
void reverseList(List list) {
Position tmp;
List new;
new = malloc(sizeof(Node));
new->next = NULL;
while (list->next != NULL) {
tmp = list->next;
list->next = list->next->next;
tmp->next = new->next;
new->next = tmp;
}
list->next = new->next;
free(new);
}
// 1, 2, 3, 4 => 2, 1, 4, 3
void twoReverseList(List list) {
Position tmp = list, swp;
while (tmp->next != NULL && tmp->next->next != NULL) {
swp = tmp->next;
tmp->next = tmp->next->next;
swp->next = tmp->next->next;
tmp->next->next = swp;
tmp = tmp->next->next;
}
}
// 探测链表是否构成环路
int detectCycle(List list) {
Position fast, slow;
fast = list->next;
slow = list;
while (fast != NULL) {
if (fast == slow) {
return 0;
}
fast = fast->next->next;
slow = slow->next;
}
return -1;
}
int main(void) {
int ret;
List l;
initList(&l);
insertList(l, 5);
insertList(l, 8);
insertList(l, 2);
insertList(l, 78);
printList(l);
reverseList(l);
printList(l);
twoReverseList(l);
printList(l);
ret = detectCycle(l);
printf("%d\n", ret);
l->next->next->next->next->next = l->next->next;
ret = detectCycle(l);
printf("%d\n", ret);
return 0;
}