C++/C recursively realize reversal of singly linked list

//

//

 

#include <stdio.h>

#include <stdlib.h>

 

typedef struct Node{

    int data;

    Node *next;

}Node;

 

void reverse(Node *head);

Node *new_head;

int count = 0;

 

int main () {

    Node *p = (Node *)malloc(sizeof(Node));

    Node *head = p;

//Create a singly linked list

    for(int i=1;i<10;++i){

        Node *q = (Node *)malloc(sizeof(Node));

        q->data = i;

        p->next = q;

        p = p->next;

    }

    p = head;

//Output this singly linked list

    while (p != NULL) {

        printf("%d",p->data);

        p = p->next;

    }

    printf("\n");

    //Call recursive function

    reverse(head);

    p = new_head;

//Output the linked list after reversal

    while (p != NULL) {

        printf("%d",p->data);

        p = p->next;

    }

    printf("\n");

    //printf("%d",count);

    return 0;

}

 

 

/*

Reverse the function, pq traverses to the end of the linked list, then changes the next of the last node to the previous node, and then repeats the recursion

 

*/

void reverse(Node *head){

    count += 1;

    Node *p,*q;

//Traversal

    p = head;

    if(p->next == NULL){

        return;

    }

    q = p->next;

    while (q->next != NULL) {

        p = q;

        q = p->next;

    }

//reverse

    q->next = p;

    if (count == 1){

        //The last node becomes the head node after reversal

        new_head = q;

    }

    p->next = NULL;

    reverse(head);

}

 

 

Guess you like

Origin blog.csdn.net/qq_39429779/article/details/109017139