主题:单链表
链表的实现(无头单向非循环链表),插入和删除选择链表,查找选择顺序表。进行链表相关操作要判断链表是否为空,出现有关下标的要判断合法性(在插入元素时,还要注意头插法和尾插法)
1.链表的定义
思路:要定义的是链表的值,node代表的是当前链表自己的地址,node.next是当前链表存的下一个链表的地址,head是指头节点元素的地址。
class Node{
public int val;
public Node next;//null
public Node(int val){
this.val=val;
}
}
public Node head;
2.创建链表
思路一:穷举的方式
public void createList() {
Node node1 = new Node(10);
Node node2 = new Node(25);
Node node3 = new Node(18);
Node node4 = new Node(39);
node1.next = node2;
node2.next=node3;
node3.next=node4;
this.head=node1;
}
思路二:头插法创建链表,改变链表当前所处位置以及存的下一个元素的地址。
public void addFirst(int data){
Node node =new Node(data);
node.next=head;
head=node;
}
3.尾插法
思路:要考虑链表是否为空。
当链表为空的情况:
当链表不为空的情况:
public void addLast(int data){
Node node=new Node(data);
if(head==null){
this.head=node;
}
else{
Node cur=this.head;
while(cur.next!=null){
cur=cur.next;
}
cur.next=node;
}
}
4.打印单链表
思路:循环
public void show(){
Node cur=this.head;
while(cur!=null){
System.out.print(cur.val+" ");
cur=cur.next;
}
}
5.得到单链表的长度
思路:count计数
public int size(){
Node cur=this.head;
int count=0;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
6.任意位置插入,第一个数据节点为0号下标
思路:先要根据下标找到这个数的前一个数index-1。因为与下标有关,因此还要判断下标的合法性,在插入中同时还要考虑插入的位置,index值为0前插法,index==size()后插法。若是中间插入见下图。
public Node searchprev(int index){
Node cur=this.head;
int count=0;
if(count!=index-1){
cur=cur.next;
count++;
}
return cur;
}
public void addIndex(int index,int data){
if(index<0||index>size()){
System.out.println("下标不合法");
return;
}
if(index==0){
addFirst(data);
return;
}
if(index==size()){
addLast(data);
return;
}
Node cur=searchprev(index);
Node node=new Node(data);
node.next=cur.next;
cur.next=node;
}
7.查找是否包含关键字key是否在单链表当中
思路:查链表中是否有值与要查的数值相等。如果相等则输出,查不到则返回false。
public boolean contains(int val){
Node cur=this.head;
while(cur!=null){
if(cur.val==val){
return true;
}
cur=cur.next;
}
return false;
}
8.删除第一次出现关键字为key的节点
思路:首先要根据数值找到要删除的数的前一个数的地址cur。随后要考虑此表是否为空表、要删除的是否是头节点。若删除的是头节点:
若删除的是中间的节点:还要判断链表中是否存在要删除的节点数值,若cur==null,则不存在。若存在:
public Node searchprev2(int val){
Node cur=this.head;
while(cur.next!=null) {
if (cur.next.val == val) {
return cur;
}
cur = cur.next;
}
return null;
}
public void remove(int val){
if(head==null){return;}
if(this.head.val==val){
head=head.next;
return;
}
Node cur=searchprev2(val);
if(cur==null){
System.out.println("没有你要找的节点");
return;
}
Node del=cur.next;
cur.next=del.next;
}
9.删除所有值为key的节点
思路:考虑链表为空的情况、头节点位置的问题。若链表不为空,也不在头节点位置:
在此问题中,最后在考虑头节点问题:若将头节点部分的程序放在第一个if之后,将会出现若前两个都是要删除的数值,则第二个会空过去的情况,因此将此部分程序放在整段程序的后面。
public void removeAllKey(int key){
if(head==null){
return;
}
Node prew=this.head;
Node cur=this.head.next;
while(cur!=null){
if(cur.val==key){
prew.next=cur.next;
cur=cur.next;
}
else{
prew=cur;
cur=cur.next;
}
}
if(this.head.val==key){
this.head=this.head.next;
}
}
10.清除链表(细腻删除)
思路:清空.next则前一个失去地址被回收。
public void clear(){
if(this.head!=null){
Node curNext=this.head.next;
this.head.next=null;
this.head=curNext;
}