/*** 链表
*@authorluminous-xin
*@param*/
public class ListLink{//头指针
private Nodehead;//单链表的长度
private intlength;//构造一个空的链表
publicListLink() {
length= 0;
head= new Node(null);
}//获取链表头节点的位置
public NodegetHead() {returnhead;
}//在链表中插入一个元素
public boolean add(T obj, intpos) {if (pos < 1 || pos > length + 1) {
System.out.println("pos值不合法");return false;
}int num = 1;
Node p = head, q =head.next;while (num
p=q;
q=q.next;
num++;
}
p.next= new Node(obj, q);
length++;return true;
}//删除链表中某各元素
public T remove(intpos) {if(isEnpty()) {
System.out.println("链表为空表");return null;
}if (pos < 1 || pos > length + 1) {
System.out.println("pos值不合法");return null;
}int num = 1;
Node p = head, q =head.next;while (num
p=q;
q=q.next;
num++;
}
p.next=q.next;
length--;returnq.data;
}//获取链表中一个元素的值
public T value(intpos) {if(isEnpty()) {
System.out.println("链表为空表");return null;
}if (pos < 1 || pos > length + 1) {
System.out.println("pos值不合法");return null;
}int num = 1;
Node p = head, q =head.next;while (num
p=q;
q=q.next;
num++;
}returnq.data;
}//在链表中查找一个元素,返回该元素下标的索引
public intfind(T obj) {if(isEnpty()) {
System.out.println("链表为空表");return -1;
}int num = 1;
Node p = head, q =head.next;while (q!= null) {if(obj.equals(q.data)) {returnnum;
}
p=q;
q=q.next;
num++;
}return -1;/*Node p = head.next;
while (p != null) {
if (p.data.equals(obj) == false) {
p = p.next;
num++;
} else break;
}
if (p == null) {
return -1;
}
return num;*/}//更新链表中某各元素
public boolean modify(T obj, intpos) {if(isEnpty()) {
System.out.println("链表为空表");return false;
}if (pos < 1 || pos > length + 1) {
System.out.println("pos值不合法");return false;
}int num = 1;
Node q =head.next;while (num
q=q.next;
num++;
}
q.data=obj;return true;
}//判空
public booleanisEnpty() {return length == 0;
}//求链表中数据元素的个数
public intsize() {returnlength;
}//一次访问链表中每个元素并输出
public voidnextOrder() {
Node q =head.next;while (q != null) {
System.out.println(q.data);
q=q.next;
}
}//销毁一个已经存在的链表
public voidclear() {
length= 0;
head.next= null;
}public static voidmain(String[] args) {
ListLink l = new ListLink<>();inti;int a[] = {23, 56, 12, 49, 35};for (i = 0; i < a.length; i++) {
l.add(a[i], i+ 1);
}
System.out.println("单链表中的数据元素为:");
l.nextOrder();
System.out.println(l.find(5));
}