#include<iostream>
using
namespace
std
;
struct
linklist
//结点
{
int
data
;
linklist
*
next
;
};
//结构体末尾记得加分号
class
linklistclass
{
private:
linklist
*
head
;
//单链表头结点指针
public:
linklistclass
();
~
linklistclass
();
void
creatlistf
(
int
a
[],
int
n
);
//头插法
void
creatlistr
(
int
a
[],
int
n
);
//尾插法
void
displist
();
//输出结点值
int
listlength
();
//链表中结点个数
bool
getelem
(
int
i
,
int
&
e
);
//求某个数据元素值
int
locateelem
(
int
e
);
//按元素值查找
bool
listinsert
(
int
i
,
int
e
);
//插入
bool
listdelete
(
int
i
);
//删除
};
linklistclass
::
linklistclass
()
{
head
=
new
linklist
();
head
->
next
=
NULL
;
}
linklistclass
::~
linklistclass
()
{
linklist
*
pre
,
*
p
;
pre
=
head
;
p
=
pre
->
next
;
while
(
p
!=
NULL
)
{
delete
pre
;
pre
=
p
;
p
=
p
->
next
;
}
delete
pre
;
}
//头插法
void
linklistclass
::
creatlistf
(
int
a
[],
int
n
)
{
linklist
*
s
;
int
i
;
head
->
next
=
NULL
;
for
(
i
=
0
;
i
<
n
;
i
++
)
{
s
=
new
linklist
();
s
->
data
=
a
[
i
];
s
->
next
=
head
->
next
;
head
->
next
=
s
;
}
}
//尾插法
void
linklistclass
::
creatlistr
(
int
a
[],
int
n
)
{
linklist
*
s
,
*
r
;
//r尾指针始终指向当前链表的尾结点 ,开始时指向头节点
int
i
;
for
(
i
=
0
;
i
<
n
;
i
++
)
{
s
=
new
linklist
();
s
->
data
=
a
[
i
];
r
->
next
=
s
;
r
=
s
;
}
r
->
next
=
NULL
;
//尾结点的指针域置为空
}
void
linklistclass
::
displist
()
{
linklist
*
p
;
p
=
head
->
next
;
while
(
p
!=
NULL
)
{
cout
<<
p
->
data
<<
" "
;
p
=
p
->
next
;
}
cout
<<
endl
;
}
int
linklistclass
::
listlength
()
{
linklist
*
p
;
int
i
=
0
;
p
=
head
;
while
(
p
->
next
!=
NULL
)
{
i
++
;
p
=
p
->
next
;
}
}
bool
linklistclass
::
getelem
(
int
i
,
int
&
e
)
{
linklist
*
p
;
int
j
=
0
;
while
(
j
<
1
&&
p
!=
NULL
)
{
j
++
;
p
=
p
->
next
;
}
if
(
p
==
NULL
)
{
return
false
;
}
else
{
e
=
p
->
data
;
return
true
;
}
}
int
linklistclass
::
locateelem
(
int
e
)
{
linklist
*
p
;
int
i
=
1
;
p
=
p
->
next
;
while
(
p
!=
NULL
&&
p
->
data
!=
e
)
{
p
=
p
->
next
;
i
++
;
}
if
(
p
==
NULL
)
return
0
;
else
return
i
;
}
bool
linklistclass
::
listinsert
(
int
i
,
int
e
)
{
linklist
*
s
,
*
p
;
int
j
=
0
;
if
(
i
<
1
)
return
false
;
p
=
head
;
while
(
j
<
i
-
1
&&
p
!=
NULL
)
{
j
++
;
p
=
p
->
next
;
}
if
(
p
==
NULL
)
return
false
;
else
{
s
=
new
linklist
();
s
->
data
=
e
;
s
->
next
=
p
->
next
;
p
->
next
=
s
;
return
true
;
}
}
bool
linklistclass
::
listdelete
(
int
i
)
{
int
j
=
0
;
linklist
*
p
,
*
q
;
if
(
i
<
1
)
return
false
;
p
=
head
;
while
(
j
<
i
-
1
&&
p
!=
NULL
)
{
j
++
;
p
=
p
->
next
;
}
if
(
p
==
NULL
)
return
false
;
else
{
q
=
p
->
next
;
if
(
q
==
NULL
)
return
false
;
p
->
next
=
q
->
next
;
//删除*q结点
delete
q
;
return
true
;
}
}
int
main
()
{
linklistclass
sail
;
int
n
;
cout
<<
"请输入链表结点数据结点的个数n "
;
cin
>>
n
;
int
a
[
20
];
cout
<<
"请输入数组元素"
<<
endl
;
for
(
int
i
=
0
;
i
<
n
;
i
++
)
cin
>>
a
[
i
];
cout
<<
"=============构建一个新链表"
<<
endl
;
sail
.
creatlistf
(
a
,
n
);
cout
<<
"=============链表构建完毕"
<<
endl
;
cout
<<
"=============输出链表"
<<
endl
;
sail
.
displist
();
return
0
;
}