单链表的反转-递归

递归

#include <stdio.h>

typedef struct{

   int data;

   struct Node* next;

}Node;

Node* CreateNode(int value) {

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

temp->data = value;

temp->next = NULL;

return temp;

}

Node* head=NULL;

void InsertNode(int value) {

Node* temp = CreateNode(value);

if(head==NULL) {head=temp;}

else {

Node* p=head;

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

p->next=temp;

}

}

void PrintLinkedList() {

if(head==NULL) {

printf("LinkedList is empty.\n");

} else {

Node* temp = head;

while(temp) {

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

temp=temp->next;

}

printf("NULL\n");

}

}

void RevertLinkedList() {

if(head==NULL || head->next==NULL) return;

Node* pre=NULL;

Node* current=head;

Node* next=head->next;

while(next) {

current->next=pre;

pre=current;

current=next;

next=next->next;

}

current->next=pre;

head=current;

}

int main()

{

   InsertNode(1);

   InsertNode(2);

   InsertNode(3);

   InsertNode(4);

   PrintLinkedList();

   RevertLinkedList();

   PrintLinkedList();

   return 0;

}

 

 

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

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

猜你喜欢

转载自www.cnblogs.com/lilideng/p/11291288.html