2.3.1 单链表 P24
package hicc.ds.c02_linear;
class LNode {
Object data;
LNode next;
public LNode(Object data) {
this.data = data;
this.next = null;
}
}
public class LinkList {
private LNode H; //链表头结点
private LNode L; //链表尾结点
public LinkList() {
H = L = null;
}
public LNode get(int i) { //按索引查找
LNode p = H;
int j = 0;
while (p != null && p.next != null && j < i) {
p = p.next;
j++;
}
return p;
}
public LNode location(Object x) { //按值查找
LNode p = H;
while (p != null && !p.data.equals(x)) {
p = p.next;
}
return p;
}
public void insert(Object x) { //添加数据
LNode n = new LNode(x);
if (H == null) {
H = L = n;
} else {
L.next = n;
L = n;
}
}
public int insert(int i, Object x) { //向指定位置添加数据
LNode p = get(i);
if (p == null) {
return -1;
} else {
LNode n = new LNode(x);
n.next = p.next;
p.next = n;
Object temp = n.data;
n.data = p.data;
p.data = temp;
return 1;
}
}
public int delete(int i) { //删除运算
LNode p = get(i-1);
if (p == null) {
return -1; //
} else {
if (p.next == null) {
return 0; //
} else {
LNode n = p.next;
p.next = n.next;
return 1;
}
}
}
public void showData() { //展示链表数据
LNode p = H;
if (p == null) {
System.out.println("null");;
} else {
while (p != null) {
System.out.print(p);
System.out.print('|');
System.out.print(p.data);
System.out.print('|');
System.out.println(p.next);
p = p.next;
}
}
}
public static void main(String[] args) {
LinkList linkList = new LinkList();
linkList.insert('A');
linkList.insert('B');
linkList.insert('C');
linkList.showData();
System.out.println(linkList.get(1));
System.out.println(linkList.location('C'));
linkList.insert(2, 'D');
linkList.showData();
linkList.delete(2);
linkList.showData();
}
}