//线性表之单链表自实现 (JDK链表:LinkedList)
public class LinkList<T> {
//定义头结点
private Node head;
//记录链表长度
private int N;
//内部节点类
private class Node{
//节点存储的数据
T data;
//该节点的下一个节点
Node next;
public Node(T data,Node next){
this.data=data;
this.next=next;
}
}
public LinkList(){
this.head=new Node(null,null);
this.N=0;
}
//向链表中新增元素
public void add(T e){
Node node = new Node(e,null);
Node n=head;//n引用head对象
//n的引用指向head的下一个节点
while (n.next!=null){
n=n.next;
}
n.next=node;
N++;
}
//中间插入节点
public void insert(int i,T e){
Node n=head;
//找到第i个节点的前一个节点
for (int a=0;a<i-1;a++){
n=n.next;
}
//创建新节点指向原理i位置的节点
Node node1 = new Node(e, n.next);
//原来i位置之前的节点指向新节点
n.next=node1;
N++;
}
public void clear(){
head.next=null;
N=0;
}
//删除指定位置i的节点
public T remove(int i){
Node n=head;
//找到i之前的一个节点
for (int a=1;a<i;a++){
n=n.next;
}
T s=n.next.data;
n.next=n.next.next;
N--;
return s;
}
public int indexOf(T t){
Node n=head.next;
for (int i = 1; i <= N; i++) {
if (n.data.equals(t)){
return i;
}
else
n=n.next;
}
//如果没有找到,返回-1
return -1;
}
public void out(){
Node node=head;
for (int i=0;i<N;i++){
System.out.println(node.next.data);
node=node.next;
}
}
//递归使所有节点反转
public Node reverse(Node n){
if (n.next==null){
head.next=n;
return n;
}
reverse(n.next);
n.next.next=n;
n.next=null;
return n;
}
//单链表反转
public void reverse(){
if (head.next==null){
return;
}else
reverse(head.next);
}
}
Java单链表实现
最新推荐文章于 2024-07-27 13:31:57 发布