线性表-链表
package suanfa.Linear;
public class LInkList<T> {
private Node head;
private int N;
public static void main(String[] args) {
LInkList<String> s = new LInkList<>();
s.insert("马");
s.insert("王");
s.insert("刘");
s.insert("朱");
s.insert("测试", 4);
for (int index = 0; index < s.length(); index++) {
System.out.println(s.get(index));
}
System.out.println("删除了: "+s.delete(0));
System.out.println("取到了: "+s.get(2));
s.indexOf("朱");
}
//结点类
private class Node{
//数据
T item;
//结点
Node next;
public Node(T item,Node next){
this.item = item;
this.next = next;
}
}
//初始化
public LInkList(){
this.head = new Node(null, null);
this.N = 0;
}
//清空
public void clear(){
head.next = null;
N = 0;
}
//返回长度
public int length(){
return N;
}
//判断是否为空
public boolean isempty(){
return N ==0;
}
//获取指定位置i出的元素
public T get(int i){
Node n = head.next;
for (int index = 0; index <i ; index++) {
n = n.next;
}
return n.item;
}
//向链表中添加元素
public void insert(T t){
//创建始结点
Node n =head;
//循环找到尾结点
while (n.next !=null){
n = n.next;
}
//创建新结点
Node newNode = new Node(t, null);
//指向
n.next = newNode;
N++;
}
//向指定位置i插入元素t
public void insert(T t, int i){
Node n = head;
for (int index = 0; index < i; index++) {
n = n.next;
}
Node originalNode = n.next;
Node newNode = new Node(t, originalNode);
n.next = newNode;
N++;
}// 0 1 2 3 i=2
//删除指定位置i处元素t,并返回元素t
public T delete(int i){
Node n = head;
for (int index = 0; index < i; index++) {
n = n.next;
}
Node originalNode = n.next;
Node newNode = originalNode.next;
n.next = newNode;
N--;
return originalNode.item;
}
//查找元素第一次出现的位置
public int indexOf(T t){
Node n = head;
for (int index = 0; index < N; index++) {
n = n.next;
if (n.item == t){
System.out.println("找到了: "+ n.item +" "+index);
break;
}
}
return 0;
}
}
1 条评论
文章结构紧凑,层次分明,逻辑严密,让人一读即懂。