首先建立一个链表,需要注意的是用模板来写类的时候,必须将类定义和类声明都放在头文件里面,这个问题以前发邮件请教过Bjarne Stroustrup ,他说这是现代编译器的规定,但没具体解释。
下面是链表的实现:
//
LinkList.h
#ifndef LINKLIST_H
#define
LINKLIST_H
#include
<
iostream
>
#ifndef NULL
#define
NULL 0
#endif
//
NULL
namespace
robert
{
template
<
class
T
>
class
LinkList;
//
The previous declaration of class LinkList
template
<
class
T
>
std::ostream
&
operator
<<
(std::ostream
&
,
const
LinkList
<
T
>&
);
//
declaration of function <<
template
<
class
T
>
class
LinkNode
{
friend
class
LinkList
<
T
>
;
friend std::ostream
&
operator
<<
<
T
>
(std::ostream
&
,
const
LinkList
<
T
>&
);
LinkNode():next(NULL) {}
T data;
LinkNode
<
T
>*
next;
};
template
<
class
T
>
class
LinkList
{
public
:
LinkList();
~
LinkList();
bool
IsEmpty()
const
;
int
Length()
const
;
bool
Insert(
const
T
&
);
//
Insert the data to the end of the LinkList
bool
Insert(
const
T
&
,
int
);
//
Insert the data at the appointed position
bool
Delete(
int
,T
&
);
//
Delete the data at the appointed position and get the data field to another parameter
bool
Find(
int
,T
&
)
const
;
bool
Change(
int
,
const
T
&
);
LinkList
<
T
>*
Sort();
//
Sort the List, the larger first
friend std::ostream
&
operator
<<
<
T
>
(std::ostream
&
,
const
LinkList
<
T
>&
);
private
:
LinkNode
<
T
>*
head;
};
template
<
class
T
>
LinkList
<
T
>
::LinkList()
{
head
=
new
LinkNode
<
T
>
;
}
template
<
class
T
>
LinkList
<
T
>
::
~
LinkList()
{
LinkNode
<
T
>*
temp;
while
(head)
{
temp
=
head
->
next;
delete head;
head
=
temp;
}
}
template
<
class
T
>
bool
LinkList
<
T
>
::IsEmpty()
const
{
return
head
==
0
;
}
template
<
class
T
>
int
LinkList
<
T
>
::Length()
const
{
LinkNode
<
T
>*
temp
=
head
->
next;
int
len
=
0
;
while
(temp)
{
len
++
;
temp
=
temp
->
next;
}
return
len;
}
template
<
class
T
>
bool
LinkList
<
T
>
::Insert(
const
T
&
x)
{
LinkNode
<
T
>*
temp
=
head;
while
(temp
->
next)
{
temp
=
temp
->
next;
}
LinkNode
<
T
>*
t
=
new
LinkNode
<
T
>
;
t
->
data
=
x;
t
->
next
=
NULL;
temp
->
next
=
t;
return
true
;
}
template
<
class
T
>
std::ostream
&
operator
<<
(std::ostream
&
out
,
const
LinkList
<
T
>&
t)
{
LinkNode
<
版权声明:本文为robertzhang10原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。