重写LinkedList的java实现简单1的方法
-
LinkedList的原理。
- 1 LinkedList是一种数据结构,其中各对象按线性顺序排列。数组的线性是顺由数组下标决定的,链表的顺序是由各个对象里的指针决定的。
- LinkedList和数组不一样,是可以很轻易的进行增上改查,不过他的查询速度很慢,只能通过首节点来找到下一个节点,依次进行查找数据。数组的查找速度很快,因为他在电脑储存的位置是连续的。数组一旦创建就无法动态更改它的大小
- LinkedList结构是以节点的形式存在。
//LinkedLis类
class LinkedList{
public Node header = null; //头节点默认为空。
public int length = 0; //这个是链表的长度。
public int size = 0;
//构造函数
class LinkedList() {
}
//节点子类
class Node {
public int data; //int类型的数据域。
public Node next = null; //下一个节点的信息。
public Node() {}
public Node(int data) {
this.data = data;
}
}
}
上面的代码是LinkedList类的基本属性,还有他的一些常用的方法,例如add(), del()方法,
- add方法类
public void addFirst(int data) {
add(data);
}
public void add(int data) {
Node node = new Node(data)
if(header == null){
this.header = node;
this.length++;
return;
}
Node temp = this.head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
this.length++;
}
}
//通过下标插入节点
public void addNode(int index,int data){
Node node = new Node(data);
Node pre = head;
Node current = head;
while(index != size){
pre = current;
current = current.next;
this.size++;
}
node.next = current;
pre.next = node;
this.length++;
this.size=0;
}
//最后一个节点
public void addLast(int data) {
Node node = new Node(data);
Node current = head;
while(current.next != null){
current = current.next;
}
current.next = node;
length++;
}
- del方法
//删除某个数据的节点
public void delBydata(int data){
Node pre = head;
Node current = head;
while(data != current.data){
pre = current;
current = current.next;
if(current.next == null){
System.out.println("数据找不到");
return ;
}
}
pre.next = current.next;
this.length--;
}
//删除某个下标的节点
public void delByIndex(int index){
Node pre = head;
Node current = head;
if(index>this.length||index<0){
System.out.println("数据找不到");
return;
}
while(this.size != index){
pre = current;
current = current.next;
this.size++;
}
pre.next = current.next ;
this.length--;
this.size=0;
}
- 查找节点的下标和显示全部节点的数据及其它
//得到全部的数据
public void getAllData(){
Node node = head;
while (this.size<this.length){
size++;
System.out.printf(node.data+" ");
node = node.next;
}
System.out.println();
}
//得到链表长度
public int getLength(){
return this.length;
}