链表

  1 #ifndef LIST_H
  2 #define LIST_H
  3 #include <iostream>
  4 template <class Type> class List;//List类的前置声明,因为在友元类中要用到
  5 
  6 
  7 template<class Type>
  8 class ListNode    
  9 {
 10     friend class List<Type>;
 11 private:
 12 
 13     Type data;//存放的数据
 14     ListNode *link;//指向下一个数据的指针
 15     ListNode(Type);//私有的构造函数,只能由友元类来调用
 16     
 17 };
 18 
 19 template<class Type>
 20 class List
 21 {
 22 public:
 23     List()
 24     {first = 0;};
 25     void Insert(Type);
 26     void Show();
 27     void Invert();
 28     void Concatenate(List<Type>);
 29     void Delete(Type);
 30 
 31 private:
 32     ListNode<Type> *first;
 33 };
 34 
 35 
 36 template <class Type>
 37 ListNode<Type>::ListNode(Type element)//构造函数的实现
 38 {
 39 
 40     data = element;
 41     link = 0;
 42 
 43 }
 44 
 45 
 46 template <class Type>
 47 void List <Type>::Insert(Type k)//insert函数的实现
 48 {
 49     ListNode<Type> *newnode = new ListNode<Type>(k); //k是存放在节点里的数据
 50     newnode->link = first;
 51     first = newnode;
 52 
 53 }
 54 
 55 template <class Type>
 56 void List <Type>::Delete(Type k)
 57 {
 58 
 59     ListNode<Type> *previous = 0;//  用来保存要删除节点的前一个节点
 60     ListNode<Type> * current;
 61     for(current = first; current && current->data !=k;  previous = current, current = current = current->link )
 62     {
 63         //什么都不做,只需要找到被删除的节点
 64     }
 65         if(current)
 66         {
 67             if(previous) previous->link = current->link;
 68             else first = first->link;
 69             delete current;//和insert中的new是一样的
 70 
 71         }
 72     
 73 }
 74 
 75 
 76 
 77 template<class Type>
 78 void List<Type>::Invert()
 79 {
 80     ListNode<Type> *p = first, *q = 0;
 81     while(p)
 82     {
 83     
 84         ListNode<Type> *r = q; q = p;
 85         p = p->link;
 86         q->link = r;
 87 
 88     }
 89     first = q;
 90 
 91 }
 92 
 93 
 94 
 95 template <class Type>
 96 void List<Type>::Show()
 97 {
 98 
 99     for(ListNode<Type> *current = first; current; current = current->link)
100     {
101     
102         std::cout << current->data;
103         if(current->link) std::cout << " -> ";
104         //头文件里要都加上std
105     }
106     std:cout << std::endl;
107 }
108 
109 #endif
 1 #include <iostream>
 2 #include "List.h"
 3 using namespace std;
 4 
 5 int main()
 6 {
 7 
 8     cout << "测试:" << endl;
 9 
10     List <int> intList;
11     intList.Insert(5);
12     intList.Insert(15);
13     intList.Insert(25);
14     intList.Insert(35);
15 
16     intList.Show();
17 
18     intList.Invert();
19     intList.Show();
20 
21     intList.Delete(15);
22     intList.Show();
23 
24 
25 
26     return 0;
27 }

 

 

 

invert函数算法没有解决。concatenate没有写。

posted @ 2012-12-16 21:28  uniquews  阅读(171)  评论(0编辑  收藏  举报