2023/12/5日 学习Java数据结构
今日学习了单链表和一部分的双向链表,还有一个月的时间就要期末考试了,但是我的数据结构还是一点也不会,只能抓紧学了
package com.ityuhao; import javax.swing.*; public class LinkList { //头节点 private Node head; //链表长度 public int length; //创建节点 public class Node{ int item; Node next; //节点的构造函数 public Node(int item, Node next){ this.item=item; this.next=next; } } //创建LinkList的对象 public LinkList(){ this.head =new Node(0,null); this.length=0; } //清空链表 public void clear(){ head.next=null; this.length=0; } //获取链表的长度 public int getLength(){ return length; } //判断链表是否为空 public boolean IsEmpty(){ return length==0; } //获取指定位置i的元素 public int get(int i){ Node n=head.next; for(int index = 0; index<i; index++){ n=n.next; } return n.item; } //向链表中插入元素 public void insert(int number){ Node n=head; while (n.next!=null){ n=n.next; } Node newNode = new Node(number,null); n.next=newNode; length++; } //在指定位置插入元素 public void insert(int i,int number){ //找到指定位置的前一个元素 Node pre =head; for(int index=0;index<=i-1;index++){ pre=pre.next; } //找到指定位置的元素 Node curr=pre.next; //创建一个新节点,将后面元素与新节点连起来 Node newNode =new Node(number,curr); //将新节点与前一个节点连接起来 pre.next=newNode; //长度加1 length++; } //删除指定位置的元素 public int remove(int i){ //找到指定位置的前一个元素,并返回删除的元素 Node pre =head; for(int index=0;index<=i-1;index++){ pre=pre.next; } //找到指定位置的元素 Node curr=pre.next; pre.next=curr.next; return curr.item; } //查找元素number在链表中第一次出现的位置 public int indexOf(int number){ Node n=head; for(int index=0;n.next!=null;index++){ n=n.next; if(n.item==number){ return index; } } return -1; } //遍历链表 public void print(){ Node n=head; while (n.next!=null){ n=n.next; System.out.print(n.item+" "); } } public static void main(String[] args) { LinkList list =new LinkList(); list.insert(11); list.insert(22); list.insert(33); list.insert(2,44); list.remove(2); list.print(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?