Algorithm Overview: Requires implementation to reverse a one-way list and consider the complexity of time.
Algorithm Analysis:
Array Method (abbreviated):
Save list elements into an array one by one and then reverse rebuild the list
Reviews: Implementing logic is the simplest and requires additional memory overhead.
Move the pointer:
Reverses the pointer of a linked list element one after another from the list header, starting with three pointers
Reviews: No additional memory overhead is required and the original linked list is changed.
Recursion:
Recursively first find the tail of the list, and then reverse the pointer
Reviews: No additional memory overhead is required and the original linked list is not changed.
Algorithm implementation:
Building a linked list structure
/*node Structure*/structnode{intdata; structnode*next;};/*add element-press stack*/voidPush (node** head,intdat) { structnode* New_node =NewNODE (); New_node->data =dat; New_node->next = *Head; *head =New_node;}/*add element-add*/voidAdd (node** Head,intdat) { structnode* New_node =NewNODE (); New_node->data =dat; New_node->next =NULL; if(*head! =NULL) { structnode* TEMP = *Head; while(Temp->next! =NULL) {Temp= temp->Next; } temp->next =New_node; } Else { *head =New_node; }}
Move pointer
/*Reverse List*/voidReverse (node**head) { structnode* pre =NULL; structnode* cur = *Head; structnode*NXT; while(cur! =NULL) { //Invert PointerNXT = cur->Next; Cur->next =Pre; //Move PointerPre =cur; Cur=NXT; } *head =pre;}
Recursive
/**/NODE* Reverse (node* head ) {if (head = = NULL | | head-> Next = NULL) { return head; } NODE* new_head = reverse (head->next); // Invert pointer Head->next->next = head; Head->next = NULL; return New_head;}
Print linked list
/**/void print (node* head) { NODE* temp = head; while (Temp! = NULL) {<< temp->data << std::endl ; = Temp->next; }}
>> Full Code
Data structure and algorithm (c + +)--Reverse linked list