一个链表程序

  1 #include<iostream>
2 #include<stdlib.h>
3 #include<time.h>
4 using namespace std;
5 enum AppendNewLine{noNewLine,addNewLine};
6 ////////////////////////////////////////////////////////////////
7 template<class T>
8 class Node
9 {
10 private:
11 Node<T>* next;
12 public:
13
14 T data;
15 Node(const T& item,Node<T>* ptr=NULL);//1
16 void InsertAfter(Node<T> *p);//2
17 Node<T>* DeleteAfter(void);//3
18 Node<T>* NextNode(void)const;//4
19 Node<T>* GetNode(const T& item,Node<T>* ptr=NULL);//5
20 void InsertFront(Node<T>* &head,T item);//6
21 void PrintList(Node<T>* head,AppendNewLine addnl);//7
22
23 };
24 ////////////////////////////////////////////////////////////////
25 template<class T>
26 Node<T>::Node(const T& item,Node<T>* ptr):data(item),next(ptr){}
27 ////////////////////////////////////////////////////////////////
28 template<class T>
29 void Node<T>::InsertAfter(Node<T> *p)//把p插在当前节点的下一个
30 {
31 p->next=next;
32 next=p;
33 }
34 ////////////////////////////////////////////////////////////////
35 template<class T>
36 Node<T>* Node<T>::DeleteAfter(void)//返回被删除点的指针
37 {
38 Node<T>* temPtr=next;
39 if(next==NULL)
40 {
41 return NULL;
42 }
43 next=temPtr->next;
44 return temPtr;
45 }
46 ////////////////////////////////////////////////////////////////
47 template<class T>
48 Node<T>* Node<T>::NextNode(void)const//返回当前节点的下一个节点
49 {
50 return next;
51 }
52 ////////////////////////////////////////////////////////////////
53 template<class T>
54 Node<T>* Node<T>::GetNode(const T& item,Node<T>* ptr)//新建一个节点,它的next指向传入的ptr
55 {
56 Node<T>* newNode;
57 newNode=new Node<T>(item,ptr);
58 if(newNode==NULL)
59 {
60 cerr<<"Memory allocate failure!"<<endl;
61 exit(1);
62 }
63 return newNode;
64 }
65 ////////////////////////////////////////////////////////////////
66 template<class T>
67 void Node<T>::InsertFront(Node<T>* &head,T item)//向链表头插入一个节点,需要输入链表头
68 {
69 head=GetNode(item,head);
70 }
71 ////////////////////////////////////////////////////////////////
72 template<class T>
73 void Node<T>::PrintList(Node<T>* head,AppendNewLine addnl)
74 {
75 Node<T>* currPtr=head;
76 while(currPtr!=NULL)
77 {
78 if(addnl==addNewLine)
79 cout<<currPtr->data<<endl;
80 else
81 cout<<currPtr->data<<"";
82 currPtr=currPtr->NextNode();
83 }
84 }
85 ////////////////////////////////////////////////////////////////
86 int main(void)
87 {
88
89 Node<int>* head=NULL;
90 Node<int>* currPtr;
91 int i,key,count=0;
92 srand((unsigned)time(NULL));
93 for(i=0;i<10;i++)
94 (*head).InsertFront(head,int(rand()%11));
95 cout<<"LIst:";
96 (*head).PrintList(head,noNewLine);
97 cout<<endl;
98 cout<<"Enter a key:";
99 cin>>key;
100 currPtr=head;
101 while(currPtr!=NULL)
102 {
103 if(currPtr->data==key)
104 count++;
105 currPtr=currPtr->NextNode();
106 }
107 cout<<"The data value"<<key<<"occurs"<<count
108 <<"times in the list"<<endl;
109 return 1;
110 }

posted on 2012-03-15 20:49  专吃兔子的大黑猫  阅读(214)  评论(0编辑  收藏  举报