乐观学习,乐观生活,才能不断前进啊!!!
我的主页:optimistic_chen
欢迎大家访问~
创作不易,大佬们点赞鼓励下吧~
文章目录
前言
上篇博客详细写了ArrayList的相关问题,包括上图(极其重要),我会在最近几篇博客中都有附上。
ArrayList的优点很明显,底层逻辑是一个数组,它通过下标去访问数据的速度非常快。但是在ArrayList任意位置插入或者删除元素时,就需要将后序元素整体往前或者往后搬移,时间复杂度为O(n),效率比较低
所以java集合框架中引入了LinkedList类,即链表结构。
链表(MySingleList)
链表,作为线性表的一种,它与顺序表截然相反:链表是一种物理存储结构 上 非连续存储结构, 数据元素的逻辑顺序是通过链表中的引用 链接次序实现的
之前C语言了解过这方面的知识C语言—链表专题,所以我们有一定的基础,我相信链表对于大家一定是熟悉的存在。我们先由易入难,先自己尝试一下单链表(MySingleList)的功能实现,为接下来的 LinkedList(无头双向链表) 打下基础.
接口
public interface IList {
public void addFirst(int data);
public void addLast(int data);
public void addIndex(int index,int data);
public boolean contains(int key);
public void remove(int key);
public void removeAllKey(int key);
public int size();
public void clear();
public void display();
}
具体功能代码
头插法
@Override
public void addFirst(int data) {
ListNode node = new ListNode(data);
node.next=head;
head=node;
}
尾插法
@Override
public void addLast(int data) {
ListNode node =new ListNode(data);
if(head==null){
head = node;
return;
}
ListNode cur=head;
while(cur.next!=null){
cur= cur.next;
}
cur.next=node;
}
任意位置插入,第一个数据节点为0号下标
@Override
public void addIndex(int index, int data) {
int len=size();
if(index<0||index>len){
System.out.println("index位置不合法");
return;
}
if(index==0){
addFirst(data);
return;
}
if(index==len){
addLast(data);
return;
}
ListNode cur=head;
while(index-1!=0){
cur=cur.next;
index--;
}
ListNode node=new ListNode(data);
node.next= cur.next