有辅助性或指示性的结点(保持往下走),定义为tmp;有实际参与操作的结点
#include <stdio.h>
#include <stdlib.h>#include <string.h>
#define LEN 11
typedef struct node {
int data;
struct node *pnext;
} node_t, *pnode_t;
pnode_t create_link()
{
int i;
pnode_t phead;
phead = (pnode_t)malloc(sizeof(node_t));
if (phead == NULL) {
printf("malloc fail.\n");
exit(-1);
}
memset(phead, 0, sizeof(node_t));
pnode_t ptail = phead;
for (i = 0; i < LEN; i++) {
pnode_t pnew = (pnode_t)malloc(sizeof(node_t));
if (pnew == NULL) {
printf("malloc fail.\n");
exit(-1);
}
memset(pnew, 0, sizeof(node_t));
pnew->data = i+1;
pnew->pnext = NULL;
ptail->pnext = pnew;
ptail = pnew;
}
return phead;
}
void swapNode(pnode_t phead){
if (phead == NULL){
printf("phead error!\n");
return;
}
pnode_t head, fir, sec, third;
head = phead;
while (head->pnext != NULL){
fir = head->pnext;
sec = fir->pnext;
if (sec == NULL){
printf("Not OU!\n");
return;
}
third = sec->pnext;
//delete fir
head->pnext = sec;
//insert fir
fir->pnext = third;
sec->pnext = fir;
head = head->pnext->pnext;
}
return;
}
void print_link(pnode_t phead)
{
pnode_t p = phead->pnext;
while (p != NULL) {
printf("%d ", p->data);
p = p->pnext;
}
printf("\n");
}
void reverse_link(pnode_t phead)
{
pnode_t p, q, ptmp;
p = phead->pnext;
q = phead->pnext->pnext;
ptmp = NULL;
while (q != NULL) {
ptmp = q->pnext;
q->pnext = p;
p = q;
q = ptmp;
}
phead->pnext->pnext = NULL;
phead->pnext = p;
}
int main(int argc, char *argv[])
{
pnode_t phead = NULL;
phead = create_link();
print_link(phead);
swapNode(phead);
//reverse_link(phead);
print_link(phead);
return 0;
}