单链表

Java数据结构

单链表

代码

package dataStructure;
class Singly_linked_list {
//定义单链表长度
private int length;
//定义值和指针
class Node {
T t;
Node next;
public Node(T t, Node next) {
this.t = t;
this.next = next;
}
}
private Node head;
//构造器初始化
public Singly_linked_list(){
head=new Node(null,null);
this.length=0;
}
//添加初始元素
public void insert(T t){
//新建对象
Node newnode=new Node(t,null);
//找到末节点
Node node=head;
while(node.next!=null){
node=node.next;
}
//找到尾结点进行添加
node.next=newnode;
this.length++;
}
//指定位置添加元素
public void insert(T t,int index){
if(index>this.length-1||index<0){
System.out.println(“所插入位置不在范围内”);
return ;
}
//插入位置的前面
Node before=head;
for(int i=0;i<index-1;i++){
before=before.next;
}
//插入位置的后面
Node after=before.next;
//改变指针的指向
Node newNode=new Node(t,null);
before.next=newNode;
newNode.next=after;
this.length++;
}
//根据索引查找元素值
public T get(int index){
if(index>this.length||index<0) {
System.out.println(“所查找的位置不在范围内”);
return null;
}
Node after=head;
for(int i=0;i<index;i++){
after=after.next;
}
return (T) after.t;
}
//删除索引位置的值
public Node remove(int index){
if(index>this.length||index<0) {
System.out.println(“所删除元素的位置不在范围内”);
return null;
}
Node before=head;
for(int i=0;i<index-1;i++){
before=before.next;
}
Node crr=head;
crr=before.next;
Node after=crr.next;
before.next=after;
this.length–;
return crr;
}
public static void main(String[] args){
Singly_linked_list singly_linked_list=new Singly_linked_list();
singly_linked_list.insert(1);
singly_linked_list.insert(2);
singly_linked_list.insert(3);
singly_linked_list.insert(4);
System.out.println(“长度:”+singly_linked_list.length);
singly_linked_list.insert(66,3);
System.out.println(“长度:”+singly_linked_list.length);
System.out.println(“该位置元素的值为:”+singly_linked_list.get(5));
singly_linked_list.remove(1);
System.out.println(“该位置元素的值为:”+singly_linked_list.get(1));
System.out.println(“长度:”+singly_linked_list.length);
}
}

运行结果

在这里插入图片描述

时间:2021年1月29日 星期五

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值