Chinaunix首页 | 论坛 | 博客
  • 博客访问: 268050
  • 博文数量: 45
  • 博客积分: 930
  • 博客等级: 准尉
  • 技术积分: 553
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-22 17:53
文章分类

全部博文(45)

文章存档

2013年(5)

2012年(40)

分类: C/C++

2012-12-11 12:00:40


点击(此处)折叠或打开

  1. #include <iostream>

  2. using namespace std;

  3. struct Node{
  4.     int data;
  5.     Node * next;
  6. };

  7. class NodeList{
  8. private:
  9.     Node * headnode;
  10. public:
  11.     NodeList(){headnode = 0;}
  12.     ~NodeList();
  13.     Node * nodeReverse();
  14.     Node * addNode(int curData);
  15.     void printNode();
  16. };

  17. NodeList::~NodeList()
  18. {
  19.     Node * gre;
  20.     while(headnode)
  21.     {
  22.         gre = headnode->next;
  23.         delete headnode;
  24.         headnode = gre;
  25.     }
  26. }
  27. Node * NodeList::nodeReverse()
  28. {
  29.     if (!headnode || !(headnode->next))
  30.     {
  31.         return headnode;
  32.     }
  33.     else
  34.     {
  35.         Node * pre = headnode;
  36.         Node * current = headnode->next;
  37.         while (current)
  38.         {
  39.             Node * post = current->next;
  40.             current->next = pre;
  41.             pre = current;
  42.             current = post;
  43.         }
  44.         headnode->next = NULL;
  45.         headnode = pre;
  46.         return headnode;

  47.     }
  48. }
  49. Node* NodeList::addNode(int curData)
  50. {
  51.     Node * y = new Node;
  52.     y->data = curData;
  53.     y->next = NULL;
  54.     if (!headnode)
  55.     {
  56.         headnode = y;
  57.     }
  58.     else
  59.     {
  60.         Node * p = headnode;
  61.         while (p->next)
  62.         {
  63.             p = p->next;
  64.         }
  65.         p->next = y;
  66.     }
  67.     return headnode;
  68. }

  69. void NodeList::printNode()
  70. {
  71.     Node * p = headnode;
  72.     while (p)
  73.     {
  74.         cout<<p->data<<" ";
  75.         p = p->next;
  76.     }
  77.     cout<<endl;
  78. }

  79. int main()
  80. {
  81.     NodeList py;
  82.     py.addNode(23);
  83.     py.addNode(34);
  84.     py.addNode(45);
  85.     py.addNode(56);
  86.     py.printNode();
  87.    
  88.     py.nodeReverse();
  89.     py.addNode(89);
  90.     py.printNode();

  91.     return EXIT_SUCCESS;
  92. }
输出结果

阅读(1339) | 评论(0) | 转发(0) |
0

上一篇:shell十三问之八

下一篇:堆排序c++实现

给主人留下些什么吧!~~