码迷,mamicode.com
首页 > 编程语言 > 详细

用C++代码实现Reverse link list

时间:2015-08-04 12:48:53      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

可能有很多种实现方式,分享一下最朴实的方法。

首先是节点和Link List结构:

struct mynode {  int value;  mynode * next; };

struct mylist {  mynode * first;  mynode * last; };

提供一些基础函数:

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; }

最关键的是反转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;  } }

 

主函数验证正常工作:

int _tmain(int argc, _TCHAR* argv[]) {  mylist myinitiallist;  list_init(&myinitiallist);

 for (int t = 1; t <= 10; 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; }

 

用C++代码实现Reverse link list

标签:

原文地址:http://www.cnblogs.com/waynejiang/p/4701507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!