2023/12/5日 学习Java数据结构

发布时间 2023-12-05 22:29:00作者: 新晋软工小白

今日学习了单链表和一部分的双向链表,还有一个月的时间就要期末考试了,但是我的数据结构还是一点也不会,只能抓紧学了

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();
    }
}