Java小程序之自定义链表的实现
一、前面我们自己实现了队列,和画板的重绘有关;今天我们实现自定义链表;
二、自定义链表实现源代码:
节点类:
package Test;
//定义节点类型
public class Node {
public int data;
public Node next;
}
自定义链表的具体实现:
package Test;
public class MyLinkedList {
//定义一个头结点
private Node head = new Node();
//节点个数属性
public int size=0;
//添加节点操作
public void add(int value){
Node node = new Node();
node.data=value;
Node nextNode =new Node();
nextNode=head;
//找到为空的下一个节点
while(nextNode.next!=null){
nextNode =nextNode.next;
}
nextNode.next=node;
size++;
}
//插入节点操作
public void insert(int value,int index){
Node node = new Node();
node.data=value;
int count=0;
Node nextNode = head;
while(count<index){
nextNode=nextNode.next;
count++;
}
node.next=nextNode.next;
nextNode.next=node;
size++;
}
//得带指定位置的节点操作
public int get(int index){
Node nextNode = new Node();
nextNode=head;
int count=0;
while(count<index){
nextNode=nextNode.next;
count++;
}
return nextNode.data;
}
//查找元素
public void search(int value){
Node nextNode =new Node();
nextNode=head;
int count=0;
while(nextNode.next!=null){
if(nextNode.next.data==value){
System.out.println("找到索引为"+count+"元素与待查找的元素相等!");
nextNode=nextNode.next;
count++;
}
else{
nextNode=nextNode.next;
count++;
}
}
}
//删除元素
public void delete(int index){
Node nextNode = new Node();
nextNode=head;
int count=0;
while(count<index){
nextNode=nextNode.next;
count++;
}
nextNode.next=nextNode.next.next;
size--;
}
//更新元素操作
public void updata( int value,int index){
Node nextNode = new Node();
nextNode=head;
int count=0;
while(count<=index){
nextNode=nextNode.next;
count++;
}
nextNode.data=value;
}
//得到大小
public int getSize(){
return size;
}
//遍历输出
public void out(){
Node nextNode = new Node();
nextNode=head.next;
while(nextNode!=null){
System.out.println(nextNode.data);
nextNode=nextNode.next;
}
}
}
自定义链表测试:
package Test;
public class Test {
public static void main(String[] args) {
MyLinkedList linked = new MyLinkedList();
linked.add(1);
linked.add(2);
linked.add(3);
linked.add(4);
linked.add(3);
linked.updata(5, 4);
linked.insert(0, 0);
linked.out();
System.out.println("=======");
linked.delete(5);
linked.add(3);
linked.out();
linked.search(3);
}
}
三、总结:
1、队列和数组的区别:数组大小不可变,队列可以动态变化;
2、队列和链表的区别:队列和链表都可以动态变化,但是,队列查找元素方便,可以直接通过下标访问,二链表只能从头开始遍历,直到找到元素才结束;但是队列在指定位置增删元素不方便,需要移动大部分元素,而链表的插入以及删除非常的方便,不需要一定元素,只需要更改引用;
3、虽然Java中提供了队列(ArrayList)和链表(LinkedListener)类,但通过自己自定义实现,自己更加清楚了底层的实现原理,以后用起来可以得心应手;
4、需要经常插入和删除,使用链表好;经常需要查找的使用队列好;