Implementing reverse link List with C + + code

Source: Internet
Author: User

There may be many ways to do it, share the most simple way.

The first is the node and link list structure:

struct Mynode {int value; Mynode * NEXT; };

struct MyList {Mynode * first; Mynode * LAST; };

Provides some basic functions:

void List_init (MyList * container) {Container->first = 0; Container->last = 0; }

BOOL List_isempty (MyList * container) {return 0 = = container->first;}

Mynode * List_first (MyList * container) {return container->first;}

Mynode * List_next (Mynode * node) {return node->next;}

void List_pushback (MyList * container, Mynode * node) {if (List_isempty (container)) {Container->first = node;  container->last = node;   } else {container->last->next = node;  container->last = node; } node->next = 0; }

Mynode * List_popfront (MyList * container) {Mynode * FrontPoint = container->first;  Container->first = frontpoint->next; return frontpoint; }

The key is to reverse the link List:

void List_reverse (MyList * container)

{Mynode * Tempfirst = container->first;

Mynode * Templast = container->last;

if (tempfirst! = templast) {container->last = Tempfirst;

Mynode * Frontnode = container->first;   Mynode * NextNode = frontnode->next;    while (NextNode! = 0) {Mynode * temp = nextnode->next;    Nextnode->next = Frontnode;    Frontnode = NextNode;   NextNode = temp; }

Container->first = Templast;  Container->last->next = 0; } }

The main function validation works correctly:

int _tmain (int argc, _tchar* argv[]) {mylist myinitiallist; List_init (&myinitiallist);

for (int t = 1; t <=; t++) {Mynode * temp = (Mynode *) malloc (sizeof (Mynode));   Temp->value = t;  List_pushback (&myinitiallist, temp); }

Mynode * a = List_first (&myinitiallist);   while (a) {printf ("%d \ n", a->value);  A = List_next (a); }

List_reverse (&myinitiallist);  Mynode * b = List_first (&myinitiallist);   while (b) {Mynode * x = b;   printf ("%d \ n", b->value);   b = List_next (b);  Free (x); }

return 0; }

Implementing reverse link List with C + + code

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.