一:什么是链表:
- 链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的
(一):分类:
二:无头单向非循环链表实现
注:此处的head表示第一个节点,并不是有头链表。有头的链表的头是一个傀儡节点。
(一)、创建节点类
class ListNode{
public int val;
public ListNode next;
public ListNode(int val){
this.val=val;
}
}
(二)、创建链表
public class MyLinkedList1{
public ListNode head;//始终指向表头
//实现各种中操作方法。
}
(三)、尾插法
public class MyLinkList1{
public ListNode head;
public void lastNode(int data){
ListNode node=new ListNode(data);
ListNode cur=this.head;
if(this.head==null){
this.head=node;
return;
}
while (cur.next!=null){
cur=cur.next;//循环。
}
cur.next=node;
node.next=null;
}
}
四、头插法
public void addFirst(int data){
ListNode node=new ListNode(data);
node.next=head;
head=node;
}
计算链表的长度
public int size(){
int count=0;
ListNode cur=this.head;
while (cur!=null){
count++;
cur=cur.next;
}
return count;
}
索引位置
//索引位置。//返回了一个节点cur.
public ListNode findIndex(int index){
ListNode cur=this.head;
while (index-1!=0){
cur=cur.next;
index--;
}
return cur;
}
任意位置插入
//任意位置插入,第一个数据节点为0号下标
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