/**
* 单链表
*
* @author xueyg
*/
public class LinkList {
Node head;
Node current;
/**
* 向链表中顺序添加节点元素
*
* @return
*/
public void add(Node node) {
if (current == null) {
head = node;
current = node;
} else {
current.next = node;
current = current.next;
}
}
/**
* 遍历链表中节点元素
*/
public void print() {
if (current == null) {
System.out.println("print():空");
} else {
Node node = head;
while (node != null) {
System.out.println("print():" + node.data);
node = node.next;
}
}
}
/**
* 获取第index个节点元素
*
* @param index
* 从1开始,表示第index个节点
* @return
*/
public Node getNode(int index) {
if (index < 1) {
return null;
}
int index0 = 0;
Node node = head;
while (node != null) {
++index0;
if (index0 == index) {
return node;
}
node = node.next;
}
return null;
}
/**
* 在第index个元素的地方添加节点
*
* @param index
* 从1开始
* @param node
*
* @return
*/
public boolean add(int index, Node node) {
if (index < 1) {
return false;
}
Node pre = getNode(index - 1);
// 第index个元素有前驱
if (pre != null) {
Node cur = pre.next;
if (cur != null) {
node.next = cur;
pre.next = node;
} else {
pre.next = node;
}
return true;
}
// 第index个元素没有前驱,
// 要么index不在链表范围内
// 要么第index个元素为head
else {
Node head = getNode(index);
if (head != null) {
node.next = head;
this.head = node;
} else {
this.head = node;
}
}
return false;
}
/**
* 删除第index个元素
*
* @param index
* 从1开始
* @return
*/
public boolean delete(int index) {
if (index < 1) {
return false;
}
Node pre = getNode(index - 1);
// 第index个元素有前驱
if (pre != null) {
Node cur = pre.next;
if (cur != null) {
Node next = cur.next;
if (next != null) {
pre.next = next;
} else {
pre.next = null;
}
return true;
}
}
// 第index个元素没有前驱,
// 要么index不在链表范围内
// 要么第index个元素为head
else {
Node cur = getNode(index);
if (cur != null) {
Node next = cur.next;
if (next != null) {
this.head = next;
} else {
this.head = null;
}
return true;
}
}
return false;
}
public static void main(String[] args) {
LinkList list = new LinkList();
System.out.println("*************add");
list.add(new Node("one"));
list.add(new Node("two"));
list.add(new Node("three"));
list.add(new Node("four"));
list.add(new Node("five"));
list.print();
System.out.println("*************add2");
list.add(1, new Node("first.0"));// 边界验证
list.add(4, new Node("midlle.n"));
list.add(8, new Node("last.x"));// 边界验证
list.print();
System.out.println("*************delete");
list.delete(8);// 边界验证
list.delete(4);
list.delete(1);// 边界验证
list.print();
}
}
/**
* 节点
*/
class Node {
String data;// 数据
Node next;// 后继
public Node(String data) {
this.data = data;
}
}
// 测试结果
// *************add
// print():one
// print():two
// print():three
// print():four
// print():five
// *************add2
// print():first.0
// print():one
// print():two
// print():midlle.n
// print():three
// print():four
// print():five
// print():last.x
// *************delete
// print():one
// print():two
// print():three
// print():four
// print():five
单链表之java实现
最新推荐文章于 2022-12-22 21:43:37 发布