前言:
最近学习数据结构,以前不知道啥是数据结构,现在学了后才知道,数据结构也可以说是对一个类的方法或者功能的开发,这里我觉得链表特别有趣,自己尝试写了一个,因为是写来方便自己理解的,所以写得比较简介,希望也能帮助初学者快速理解链表
具体实现:
public class MyLinkedList<T>{
private int size;//链表长度
private Node head;//第一个对象
public MyLinkedList(){
this.size = 0;
this.head = null;
}
//由于这个类是只限自己使用,所以是私有的
private class Node{
T element;//存储自身数据
Node next;//存储下一个对象的地址,由于是引用变量,在栈中分配空间,存储的是引用对象的内存地址
public Node(T element){
this.element = element;
this.next = null;
}
public Node(T element,Node next){
this.element = element;
this.next = next;
}
@Override
public String toString(){
if(this.next == null){
return "{" +this.element.toString()+"}";
}
return "{" +this.element.toString()+"}," + this.next.toString();
}
}
//查找链表长度
public int getSize(){
return this.size;
}
//查找某一处的元素
public T findIndexOf(int n){
indexOf(n);
//查找第一个元素的数据
if(n == 0){
return this.head.element;
}
Node self = this.head;
for (int i = 1; i <= n; i++) {
self = self.next;
}
return self.element;
}
//添加元素
public void add(T element){
if(this.size == 0){
this.head = new Node(element);
this.size++;
return;
}
Node self = this.head;
for (int i = 0; i < this.size - 1; i++) {
self = self.next;
}
self.next = new Node(element);
this.size++;
}
//添加一个元素到头部
public void addFrist(T element){
Node self = this.head;
this.head = new Node(element,self);
this.size++;
}
//在尾部添加一个元素
public void addEnd(T element){
add(element);
}
//向某一个位置添加一个元素
public void setElement(int index,T element){
indexOf(index);//判断元素索引是否越界
//头部添加元素
if(index == 0){
addFrist(element);
}
Node self = this.head;
Node self2 = null;
for (int i = 1; i <= index; i++) {
self2 = self;//前一个元素
self = self.next;//当前索引的元素
}
self2.next = new Node(element,self);//插入元素
this.size++;
}
//删除某一处索引的元素
public void delete(int index){
indexOf(index);//判断索引是否越界
Node self1 = null;
Node self2 = this.head;
Node self3 = self2.next;
if(index == 0){
this.head = self3;
this.size--;
return;
}
for (int i = 1; i <= index; i++) {
self1 = self2;//前一个元素
self2 = self2.next;//当前索引元素,即i位置存储的元素
self3 = self3.next;//下一个元素
}
self1.next = self3;
this.size--;
}
//删除所有元素
public void removeAll() {
this.head = null;
this.size = 0;
}
//------------------------------------------------
//本类中自己使用的公共方法区域
//判断索引是否越界
private void indexOf(int index){
if(index >= this.size|| index < 0){
new Exception("索引越界");
}
}
@Override
public String toString(){
return "LinkedList ["+this.head.toString() +"]";
}
}
结语
因为是 简单理解,所以写得不是很严谨,只为入门,还有不足之处欢迎指出,我及时更正。
数据结构特别有意思,欢迎找我探讨