單鏈表的反轉-遞歸

#include <stdio.h>io

typedef struct {List

int data;next

struct Node* next;di

}Node;while

 

Node* CreateNewNode(int value) {data

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

temp->data = value;return

temp->next = NULL;void

return temp;printf

}

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

相關文章
相關標籤/搜索