在实际应用中链表的使用非常普遍,应该用心领会,学习一下代码,弄明白意思
package java11to20;
public class D13_LinkedList {
class Node {
int data;
Node next;
public Node(int Value) {
data = Value;
next = null;
}
}
Node header;
public static void main(String[] args) {
// TODO Auto-generated method stub
D13_LinkedList FirstList = new D13_LinkedList();
System.out.println("初始化列表:" + FirstList.toLinkListStr());
for (int i = 0; i < 10; i++) {
FirstList.insert(0, i);
}
System.out.println("数据插入列表后: " + FirstList.toLinkListStr());
FirstList.insert(11, 18);
FirstList.delete(6);
FirstList.delete(1);
System.out.println("1.删除该位置数据后列表为:" + FirstList.toLinkListStr());
System.out.println(String.format("数值5是在列表第%s位", FirstList.locate(5) + 1));
FirstList.delete(0);
System.out.println("2.删除该位置数据后列表为:" + FirstList.toLinkListStr());
for (int i = 0; i < 7; i++) {
FirstList.delete(0);
System.out.println("第" + (i + 1) + "次删除后,列表值为:" + FirstList.toLinkListStr());
}
}
public D13_LinkedList() {
header = new Node(0);
}
public boolean insert(int Position, int Value) {
Node node = header;
Node newNode;
for (int i = 0; i < Position; i++) {
if (node.next == null) {
System.out.println(String.format("第%s位置,插入数据非法", Position));
return false;
}
node = node.next;
}
newNode = new Node(Value);
newNode.next = node.next;
node.next = newNode;
return true;
}
public boolean delete(int Position) {
if (header.next == null) {
System.out.println("该列表为空。");
return false;
}
Node node = header;
for (int i = 0; i < Position; i++) {
if (node.next.next == null) {
System.out.println(String.format("位置%s非法", Position));
return false;
}
node = node.next;
}
node.next = node.next.next;
return true;
}
public void reset() {
header.next = null;
}
public String toLinkListStr() {
String result = "";
if (header.next == null) {
return "空列表";
}
Node node = header.next;
while (node != null) {
result += node.data + ", ";
node = node.next;
}
return result;
}
public int locate(int Value) {
int Position = -1;
Node node = header.next;
int CurrentPosition = 0;
while (node != null) {
if (node.data == Value) {
Position = CurrentPosition;
break;
}
node = node.next;
CurrentPosition++;
}
return Position;
}
}
输出结果:
初始化列表:空列表
数据插入列表后: 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
第11位置,插入数据非法
1.删除该位置数据后列表为:9, 7, 6, 5, 4, 2, 1, 0,
数值5是在列表第4位
2.删除该位置数据后列表为:7, 6, 5, 4, 2, 1, 0,
第1次删除后,列表值为:6, 5, 4, 2, 1, 0,
第2次删除后,列表值为:5, 4, 2, 1, 0,
第3次删除后,列表值为:4, 2, 1, 0,
第4次删除后,列表值为:2, 1, 0,
第5次删除后,列表值为:1, 0,
第6次删除后,列表值为:0,
第7次删除后,列表值为:空列表