C + + recursive and non-recursive implementation of chain list reverse order

Source: Internet
Author: User

Test environment: VS2010 Windows7

In reverse order, recursive call and chain-head interpolation were used to realize reverse order.

The specific code is as follows:

#include <iostream> #include <stdlib.h>using namespace Std;class linklist{private:struct node{struct Node * Next;int value;}; Node *phead;void reverse_use_recursion (node *pnode) {if (pnode==nullptr| | PNODE-&GT;NEXT==NULLPTR) {Phead=pnode;return;} Reverse_use_recursion (Pnode->next);p node->next->next=pnode;pnode->next=nullptr;} Public:linklist () {phead=nullptr;} void Initlinklist () {cout<< "initialize linked list with-1 end" <<endl;int tmp; Node *ptmp;cin>>tmp;while (tmp!=-1) {if (phead==nullptr) {phead=new node;phead->next=nullptr;phead-> Value=tmp;ptmp=phead;} Else{ptmp->next=new Node;ptmp=ptmp->next;ptmp->value=tmp;ptmp->next=nullptr;} Cin>>tmp;}} void print () {Node *pnode=phead;while (pnode!=nullptr) {cout<<pnode->value<<endl;pnode=pnode-> Next;}} void Clear () {node *pnode=phead;while (pnode!=nullptr) {node *ptmp=pnode;pnode=pnode->next;delete ptmp;} Phead=nullptr;} void Reverse_recursion ()//using recursive reverse order {Node *pnode=phead;reverse_use_recursion (pnode);} void ReveRse_recycle ()//using the list of head insertion method to achieve reverse {Node *pnode=phead;phead=nullptr; Node *ptmp;while (pnode!=nullptr) {if (phead==nullptr) {phead=pnode;ptmp=pnode;pnode=pnode->next;ptmp->next= nullptr;} else{ptmp=phead;phead=pnode;pnode=pnode->next;phead->next=ptmp;}}} ~linklist () {this->clear ();}}; int main () {linklist li;li.initlinklist (); Li.print (); li.reverse_recycle (); Li.print (); Li.reverse_recursion (); Li.print (); System ("pause"); return 0;}


Copyright NOTICE: Welcome to reprint, if there are deficiencies, please treatise.

C + + recursive and non-recursive implementation of chain list reverse order

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.