1.头插法:
//头插法
public void addFirst(int data){
ListNode2 node=new ListNode2(data);
if(this.head==null){
this.head=node;
this.last=node;
}else {
node.next=this.head;
this.head.prev=node;
this.head=node;//新的头指向node
}
}
2.尾插法:
//尾插法
public void addLast(int data){
ListNode2 node=new ListNode2(data);
if(this.head==null){
this.head=node;
this.last=node;
}else {
this.last=node;
node.prev=this.last;
this.last=node;
}
}
3.删除第一次出现关键字为key的值:
//删除第一次出现的关键字为key的节点
public void remove(int key){
ListNode2 node=new ListNode2(key);
ListNode2 cur=this.head;
while (cur!=null){
if(cur.val==key){
if(cur==head){
head=head.next;
head.prev=null;
}else if (cur==last){
last=last.prev;
last.next=null;
}else {
cur.next.prev=cur.prev;
cur.prev.next=cur.next;
}
return;
}
cur=cur.next;
}
}
如果只有一个节点并且删除,会出现空值异常。应该改为:
public void remove(int key){
ListNode2 node=new ListNode2(key);
ListNode2 cur=this.head;
while (cur!=null){
if(cur.val==key){
if(cur==head){
head=head.next;
if(head!=null){
head.prev=null;//如果只有一个节点,并且删除的话,直接让head的前驱为空
}else {
last=null;//只有一个节点,last也应该为空
}
}else if (cur==last){
last=last.prev;
last.next=null;
}else {
cur.next.prev=cur.prev;
cur.prev.next=cur.next;
}
return;
}
cur=cur.next;
}
}
4.任意位置插入,第一个数据节点为0号下标:
//任意位置插入,第一个数据节点为0号下标
public void addIndex(int index,int data){
ListNode2 node=new ListNode2(data);
if(index<0||index>size()){
System.out.println("不合法");
return;
}
if(index==0){
addFirst(data);
return;
}
if (index==size()){
addLast(data);
return;
}
ListNode2 ret=searchindex(index);
node.next=ret.prev.next;
ret.prev.next=node;
node.prev=ret.prev;
ret.prev=node;
}
//找到下标为index的节点
public ListNode2 searchindex(int index){
ListNode2 cur=this.head;
while (index>0){
cur=cur.next;
index--;
}
return cur;
}
5.清楚链表:
//清除链表元素
public void clear(){
while (head!=null){
ListNode2 curNext=head.next;
head.next=null;
head.prev=null;
head=curNext;
}
last=null;
}
面试问题总结:
1.顺序表和链表的区别?问区别,从共同点出发回答
①顺序表底层是数组,逻辑上和物理上都是连续的;链表是由若干节点组成的数据结构,逻辑上是连续的,内存(物理)上不一定连续。
②顺序表适合查找相关操作,因为可以直接使用下标;链表适合于频繁的插入删除操作,不需要像顺序表一样移动元素,链表的插入只需要修改指向即可。
③顺序表如果满了之后要扩容,空间利用率不高。
顺序表 | 链表: |
空白连续,支持随机访问 | 以节点为单位存储,不支持随机访问; |
中间或前面部分的插入删除时间复杂度为O(N) | 任意位置插入删除时间复杂度为O(1) |
增容的代价大 | 没有增容问题,插入一个开辟一个空间 |
2.数组和链表的区别?
3.ArryList和LinkedList的区别?
是集合框架的两个类,集合框架就算将所有的数据结构封装成Java自己的类,要是用顺序表,直接用ArryList即可。