带tail尾指针的写法:
1 |
#include
<iostream> |
02 |
using namespace std; |
03 |
class linklist
{ |
04 |
private: |
05 |
class linknode
{ |
06 |
public: |
07 |
int data; |
08 |
linknode
*next; |
09 |
linknode():next(NULL)
{} |
10 |
linknode(int d):data(d),next(NULL)
{} |
11 |
}; |
12 |
linknode
*head, *tail; |
13 |
public: |
14 |
linklist()
{ |
15 |
head=new linknode(); |
16 |
tail=head; |
17 |
} |
18 |
void add(int data)
{ |
19 |
linknode
*temp=new linknode(data); |
20 |
21 |
tail->next=temp; |
22 |
tail=temp; |
23 |
} |
24 |
void display()
{ |
25 |
linknode
*p=head->next; |
26 |
while(p->next)
{ |
27 |
cout<<p->data<<'
'; |
28 |
p=p->next; |
29 |
} |
30 |
cout<<p->data<<endl; |
31 |
} |
32 |
}; |
33 |
int main()
{ |
34 |
int n; |
35 |
cin>>n; |
36 |
linklist
x; |
37 |
while(n--)
{ |
38 |
int a; |
39 |
cin>>a; |
40 |
x.add(a); |
41 |
} |
42 |
x.display(); |
43 |
return 0; |
44 |
} |

被折叠的 条评论
为什么被折叠?



