[C]链表

来源:互联网 发布:人死犯冷退的算法 编辑:程序博客网 时间:2024/06/05 02:49
#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=NUllstruct 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();}

输出结果
输出结果

0 0