链表逆序排序

代码如下:

struct NodeList{

    int data;

    struct NodeList * next;

};

void test(){

    struct NodeList * header = malloc(sizeof (struct NodeList));

    struct NodeList * node2 = malloc(sizeof (struct NodeList));

    struct NodeList * node3 = malloc(sizeof (struct NodeList));

    struct NodeList * node4 = malloc(sizeof (struct NodeList));

    struct NodeList * node5 = malloc(sizeof (struct NodeList));

    header->data = -1;

    header->next = node2;

    node2->data = 200;

    node2->next = node3;

    node3->data = 300;

    node3->next = node4;

    node4->data = 400;

    node4->next = node5;

    node5->data = 500;

    node5->next = NULL;

    //逆序排序

    if(header->next == NULL){

        return;

    }

    struct NodeList * preNode = NULL;

    struct NodeList * currNode = header->next;

    struct NodeList * nextNode = currNode->next;

    while (nextNode != NULL) {

        currNode->next = preNode;

        preNode = currNode;

        currNode = nextNode;

        nextNode = currNode->next;

    }

    currNode->next = preNode;

    header->next = currNode;

    struct NodeList * theCurNode = header;

    while (theCurNode->next != NULL) {

        printf("--%d\n",theCurNode->next->data);

        theCurNode = theCurNode->next;

    }

    //释放

     theCurNode = header;

     struct NodeList * tempNode = NULL;

     while (theCurNode != NULL) {

         tempNode = theCurNode;

         theCurNode = theCurNode->next;

         free(tempNode);

         tempNode = NULL;

     }

}

int main()

{

  test();

return 0;

}

打印结果:

代码截图:

你可能感兴趣的:(链表逆序排序)