单链表的反转-递归

mac2022-06-30  115

#include <stdio.h>

typedef struct {

int data;

struct Node* next;

}Node;

 

Node* CreateNewNode(int value) {

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

temp->data = value;

temp->next = NULL;

return temp;

}

Node* CreateLinkedList(Node* head, int value){

Node* temp = CreateNewNode(value);

if(head==NULL) head=temp;

else {

Node* p = head;

while(p->next) { p = p->next;}

p->next = temp;

}

return head;

}

void PrintLinkedList(Node* head){

if(head==NULL) printf("The linkedlist is empty.");

else {

Node* temp=head;

while(temp) {

printf(" %d => ",temp->data);

temp=temp->next;

}

printf("NULL\n");

}

}

Node* ReverseLinkedList(Node* head) {

if(head==NULL||head->next==NULL) {

return head;

}

Node* newNode = ReverseLinkedList(head->next);

Node* next = head->next;

next->next = head;

head->next = NULL;

return newNode;

}

int main()

{

   Node* head=NULL;

   head=CreateLinkedList(head, 1);

   head=CreateLinkedList(head, 2);

   head=CreateLinkedList(head, 3);

   head=CreateLinkedList(head, 4);

   PrintLinkedList(head);

   head=ReverseLinkedList(head);

   PrintLinkedList(head);

   return 0;

}

 1 =>  2 =>  3 =>  4 => NULL

 4 =>  3 =>  2 =>  1 => NULL

 

 

转载于:https://www.cnblogs.com/lilideng/p/11291288.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)