#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node * next;
};
//获取一个节点,返回节点地址
struct Node * getNode(int data){
struct Node *node = malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
//初始化链表,返回头节点,data=0,next=NUll
struct Node * InitList(){
return getNode(0);
}
//在节点pn后插入节点pi,并更新头节点data域
void InsAfter(struct Node * list,struct Node *pn,struct Node *pi){
pi->next = pn->next;
pn->next = pi;
list->data++;
}
//删除pn节点之后的一个节点,同时更新头节点data域
int DelAfter(struct Node * list,struct Node *pn){
int data;
struct Node * tmp;
if(pn->next != NULL){
tmp = pn->next;
data = tmp->data;
pn->next = tmp->next;
free(tmp);
list->data ++;
return data;
}
else{
printf("当前节点是链表尾节点,无法执行删除操作");
exit(1);
}
}
//获取链表最后一个节点
struct Node * getLast(struct Node * list){
while(1){
if(list->next == NULL){
return list;
}
list = list->next;
}
}
//删除最后一个节点
void DelLast(struct Node * list){
struct Node *p=list,*q=NULL;
while(1){
if(p->next == NULL){
DelAfter(list,q);
break;
}
else{
q = p;
p = p->next;
}
}
}
//释放链表空间,但保留头节点,并重置头节点信息(data=0,next=NULL)
void destroy(struct Node * list){
struct Node * tmp;
struct Node * head = list;
list = list->next;
while(list != NULL){
tmp = list->next;
free(list);
list = tmp;
}
head->data = 0;
head->next = NULL;
}
//反转链表
void Reverse(struct Node * list){
void TurnAround(struct Node * list ,struct Node * node1,struct Node * node2){
if(node2->next == NULL){
list->next = node2;
node2->next = node1;
node1->next = NULL;
}
else{
TurnAround(list,node2,node2->next);
node2->next = node1;
node1->next = NULL;
}
}
TurnAround(list,list->next,list->next->next);
}
int main(int arg,char * args[]){
struct Node * list1,* list2;
struct Node * p1,* p2;
int i=0;
list1 = InitList();
list2 = InitList();
p1 = list1;
p2 = list2;
for(i=0;i<10;i++){
InsAfter(list1,p1,getNode(i));
InsAfter(list2,p2,getNode(i+10));
p1 = p1->next;
p2 = p2->next;
}
Reverse(list1);
Reverse(list2);
printf("list1:%d---list2:%d",list1->data,list2->data);
p1 = list1->next;
p2 = list2->next;
printf("\n---list1\n");
while(p1 != NULL){
printf(" %d ",p1->data);
p1 = p1->next;
}
printf("\n---list2\n");
while(p2 != NULL){
printf(" %d ",p2->data);
p2 = p2->next;
}
getchar();
}
输出结果