链表的反转-非递归

mac2022-06-30  98

#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

 

 

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

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