package
nodelist;
public
class
LinkListTest {
public
Node
head
=
new
Node();
// 定义一个头节点
public
LinkListTest() {
}
/**
* 添加一个节点
*
*
@param
data
*/
public
void
addNode(
int
data) {
Node node =
new
Node(data);
Node temp =
head
;
while
(temp.
next
!=
null
) {
temp = temp.
next
;
}
temp.
next
= node;
}
/**
* 插入某位置节点
*
*
@param
index
*
@param
node
*/
public
void
insertNodeByIndex(
int
index, Node node) {
if
(index < 1 || index > getListLength()) {
System.
out
.println(
“插入位置不合法”
);
return
;
}
Node temp =
head
;
int
length = 1;
// 记录光标位置
while
(temp.
next
!=
null
) {
if
(index == length) {
// 找到要插入的位置,进行插入操作,
node.
next
= temp.
next
;
temp.
next
= node;
}
else
{
temp = temp.
next
;
}
length++;
}
}
/**
* 删除某位置的节点
*
*
@param
index
*/
public
void
deleteNodeByIndex(
int
index) {
if
(index < 1 || index > getListLength()) {
System.
out
.println(
“删除位置不合法”
);
}
Node temp =
head
;
int
length = 1;
while
(temp.
next
!=
null
) {
if
(index == length) {
temp.
next
= temp.
next
.
next
;
return
;
}
else
{
temp = temp.
next
;
}
length++;
}
}
public
int
getListLength() {
int
length = 0;
Node temp =
head
;
while
(temp.
next
!=
null
) {
length++;
temp = temp.
next
;
}
return
length;
}
/**
* 查找所有的节点
*/
public
void
displayAllNodes() {
Node temp =
head
;
while
(temp.
next
!=
null
) {
temp = temp.
next
;
System.
out
.println(temp.
data
);
}
}
/**
*
@param
args
*/
public
static
void
main(String[] args) {
LinkListTest list =
new
LinkListTest();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.insertNodeByIndex(1,
new
Node(10));
list.displayAllNodes();
System.
out
.println(
“————–”
);
list.deleteNodeByIndex(1);
list.displayAllNodes();
// System.out.println(list.getListLength());
}
}