【Java数据结构与算法】线性表


线性表的介绍

线性表是最基本、最简单、也是最常用的一种数据结构。一个线性表是n个具有相同特性的数据元素的有限序列。

在这里插入图片描述
前驱元素:
      若A元素在B元素的前面,则称A为B的前驱元素

后继元素:
      若B元素在A元素的后面,则称B为A的后继元素

线性表的特征:数据元素之间具有一种“一对一”的逻辑关系。

  1. 第一个数据元素没有前驱,这个数据元素被称为头结点;
  2. 最后一个数据元素没有后继,这个数据元素被称为尾结点;
  3. 除了第一个和最后一个数据元素外,其他数据元素有且仅有一个前驱和一个后继。

      如果把线性表用数学语言来定义,则可以表示为(a1,…ai-1,ai,ai+1,…an),ai-1领先于ai,ai领先于ai+1,称ai-1是ai的
前驱元素,ai+1是ai的后继元素

在这里插入图片描述

线性表的分类:
      线性表中数据存储的方式可以是顺序存储,也可以是链式存储,按照数据的存储方式不同,可以把线性表分为顺序
表和链表。


一、顺序表

顺序表是在计算机内存中以数组的形式保存的线性表,线性表的顺序存储是指用一组地址连续的存储单元,依次存储线性表中的各个元素、使得线性表中再逻辑结构上响铃的数据元素存储在相邻的物理存储单元中,即通过数据元素物理存储的相邻关系来反映数据元素之间逻辑上的相邻关系。

在这里插入图片描述


1.1 顺序表的实现

顺序表API设计:

类名SequenceList< T > (泛型T 用顺序表存储任意类型数据)
构造方法SequenceList(int capacity):创建容量为capacity的SequenceList对象
成员方法见下文

1.public void clear( ):空置线性表
2.publicboolean isEmpty( ):判断线性表是否为空,是返回true,否返回false
3.public int length( ):获取线性表中元素的个数
4.public T get(int i):读取并返回线性表中的第i个元素的值
5.public void insert(int i,T t):在线性表的第i个元素之前插入一个值为t的数据元素。
6.public void insert(T t):向线性表中添加一个元素t
7.public T remove(int i):删除并返回线性表中第i个数据元素。
8.public int indexOf(T t):返回线性表中首次出现的指定的数据元素的位序号,若不存在,则返回-1。

成员变量1.private T[ ] eles:存储元素的数组 2.private int N:当前线性表的长度

分析:
①我们是基于数组来实现顺序表,真正底层存储元素的是数组,因此成员变量是泛型数组eles
②N用来记录已经存进数组的元素个数

顺序表的代码实现:

public class SequenceList<T> {
    //存储元素的数组
    private T[] eles;
    //记录当前元素个数
    private int N;

    //构造方法
    public SequenceList(int capacity){
        //初始化数组T
        this.eles = (T[]) new Object[capacity];//不能直接写new T[capacity],所以用Object代替再强转为T[]
        //初始化元素个数
        this.N = 0;
    }

    //将一个线性表置为空表
    public void clear(){
        N = 0;
    }

    //获取线性表的长度
    public int length(){
        return N;
    }

    //判断当前线性表是否为空表
    public boolean isEmpty(){
        return N==0;
    }

    //获取指定位置的元素
    public T get(int i){
        if (i<0 || i>=N){
            System.out.println("当前元素不存在!");
        }

        return eles[i];
    }

    //向线型表中添加元素t
    public void insert(T t){
        if (N == eles.length){
            throw new RuntimeException("当前表已满");
        }
        eles[N++] = t;
    }

    //向线性表i位置添加元素t
    public void inserta(int i , T t){
        if (N == eles.length){
            System.out.println("当前表已满");
        }
        if (i<0 || i>N){
            System.out.println("插入的位置不合法");
        }
        //先把i后的元素向后移一位
        for (int index = N ; index > i ; index--){
            eles[index] = eles[index-1];
        }
        //把t元素插入索引i位置
        eles[N++] = t;//巧妙写法,先把N的值作为eles数组索引然后将t赋值后,N再自增1
    }

    //删除指定位置i处的元素,并返回该元素
    public T remove(int i){
        if (i<0 || i>N-1){
            throw new RuntimeException("当前要删除的元素不存在");
        }

        T result = eles[i];
        //数据前移
        for (int index = i ; index < N - 1 ;index++){
            eles[index] = eles[index + 1];
        }
        //记录删除的元素值
        return result;
    }
    //查找t元素第一次出现的位置
    public int indexOf(T t){
        if(t==null){
            throw new RuntimeException("查找的元素不合法");
        }
        for (int i = 0; i < N; i++) {
            if (eles[i].equals(t)){
                return i;
            }
        }
        return -1;
    }
}

//测试代码
public class SequenceListTest {
    public static void main(String[] args) {
//创建顺序表对象
        SequenceList<String> sl = new SequenceList<>(10);
//测试插入
        sl.insert("姚明");
        sl.insert("科比");
        sl.insert("麦迪");
        sl.inserta(1,"詹姆斯");
//测试获取
        String getResult = sl.get(1);
        System.out.println("获取索引1处的结果为:"+getResult);
//测试删除
        String removeResult = sl.remove(0);
        System.out.println("删除的元素是:"+removeResult);
//测试清空
        sl.clear();
        System.out.println("清空后的线性表中的元素个数为:"+sl.length());
    }
}

1.2顺序表的遍历

一般作为容器存储数据,都需要向外部提供遍历的方式,因此我们需要给顺序表提供遍历方式。

在java中,遍历集合的方式一般都是用的是foreach循环,如果想让我们的SequenceList也能支持foreach循环,则
需要做如下操作:

1.让SequenceList实现Iterable接口,重写iterator方法;
2.在SequenceList内部提供一个内部类SIterator,实现Iterator接口,重写hasNext方法和next方法;

 @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator{
        private int cusor;
        public SIterator(){
            this.cusor=0;
        }
        @Override
        public boolean hasNext() {//判断容器还有没有下一个元素
            return cusor<N;
        }

        @Override
        public Object next() {//获取当前容器中的下一个元素
            return eles[cusor++];
        }

测试代码:

import cn.itcast.algorithm.linear.SequenceList;


public class SequenceListTest {

    public static void main(String[] args) {
        //创建顺序表对象
        SequenceList<String> sl = new SequenceList<>(10);
        //测试插入
        sl.insert("姚明");
        sl.insert("科比");
        sl.insert("麦迪");
        sl.insert(1,"詹姆斯");

        for (String s : sl) {
            System.out.println(s);
        }

        System.out.println("------------------------------------------");

        //测试获取
        String getResult = sl.get(1);
        System.out.println("获取索引1处的结果为:"+getResult);
        //测试删除
        String removeResult = sl.remove(0);
        System.out.println("删除的元素是:"+removeResult);
        //测试清空
        sl.clear();
        System.out.println("清空后的线性表中的元素个数为:"+sl.length());
    }
}

1.3 顺序表的容量可变

      在之前的实现中,当我们使用SequenceList时,先new SequenceList(5)创建一个对象,创建对象时就需要指定容器的大小,初始化指定大小的数组来存储元素,当我们插入元素时,如果已经插入了5个元素,还要继续插入数据,则会报错,就不能插入了。这种设计不符合容器的设计理念,因此我们在设计顺序表时,应该考虑它的容量的伸缩性。

      考虑容器的容量伸缩性,其实就是改变存储数据元素的数组的大小,那我们需要考虑什么时候需要改变数组的大小?

1.添加元素时:
      添加元素时,应该检查当前数组的大小是否能容纳新的元素,如果不能容纳,则需要创建新的容量更大的数组,我们这里创建一个是原数组两倍容量的新数组存储元素。

在这里插入图片描述
2.移除元素时:
      移除元素时,应该检查当前数组的大小是否太大,比如正在用100个容量的数组存储10个元素,这样就会造成内存空间的浪费,应该创建一个容量更小的数组存储元素。如果我们发现数据元素的数量不足数组容量的1/4,则创建一个是原数组容量的1/2的新数组存储元素。

在这里插入图片描述

 //根据参数newSize,重置eles的大小
    public void resize(int newSize){
        //定义一个临时数组,指向原数组
        T[] temp=eles;
        //创建新数组
        eles=(T[])new Object[newSize];
        //把原数组的数据拷贝到新数组即可
        for(int i=0;i<N;i++){
            eles[i]=temp[i];
        }
    }
//向线型表中添加元素t
    public void insert(T t){
        if (N==eles.length){
            resize(2*eles.length);
        }

        eles[N++]=t;
    }
//在i元素处插入元素t
    public void insert(int i,T t){
        if (N==eles.length){
            resize(2*eles.length);
        }

        //先把i索引处的元素及其后面的元素依次向后移动一位
        for(int index=N;index>i;index--){
            eles[index]=eles[index-1];
        }
       
         //把t元素插入索引i位置
        eles[N++] = t;
    }
//缩容 小于四分之一重置大小
  if (N<eles.length/4){
            resize(eles.length/2);
        }

1.4顺序表的总体代码

package cn.itcast.algorithm.linear;

import java.util.Iterator;

public class SequenceList<T> implements Iterable<T>{
    //存储元素的数组
    private T[] eles;
    //记录当前顺序表中的元素个数
    private int N;

    //构造方法
    public SequenceList(int capacity){
        //初始化数组
        this.eles=(T[])new Object[capacity];
        //初始化长度
        this.N=0;
    }

    //将一个线性表置为空表
    public void clear(){
        this.N=0;
    }

    //判断当前线性表是否为空表
    public boolean isEmpty(){
       return N==0;
    }

    //获取线性表的长度
    public int length(){
        return N;
    }

    //获取指定位置的元素
    public T get(int i){
        return eles[i];
    }

    //向线型表中添加元素t
    public void insert(T t){
        if (N==eles.length){
            resize(2*eles.length);
        }

        eles[N++]=t;
    }

    //在i元素处插入元素t
    public void insert(int i,T t){
        if (N==eles.length){
            resize(2*eles.length);
        }

        //先把i索引处的元素及其后面的元素依次向后移动一位
        for(int index=N;index>i;index--){
            eles[index]=eles[index-1];
        }
        //再把t元素放到i索引处即可
        eles[N++]=t;
    }

    //删除指定位置i处的元素,并返回该元素
    public T remove(int i){
        //记录索引i处的值
        T current = eles[i];
        //索引i后面元素依次向前移动一位即可
        for(int index=i;index<N-1;index++){
            eles[index]=eles[index+1];
        }
        //元素个数-1
        N--;

        if (N<eles.length/4){
            resize(eles.length/2);
        }

        return current;
    }


    //查找t元素第一次出现的位置
    public int indexOf(T t){
        for(int i=0;i<N;i++){
            if (eles[i].equals(t)){
                return i;
            }
        }
        return -1;
    }

    //根据参数newSize,重置eles的大小
    public void resize(int newSize){
        //定义一个临时数组,指向原数组
        T[] temp=eles;
        //创建新数组
        eles=(T[])new Object[newSize];
        //把原数组的数据拷贝到新数组即可
        for(int i=0;i<N;i++){
            eles[i]=temp[i];
        }
    }


    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator{
        private int cusor;
        public SIterator(){
            this.cusor=0;
        }
        @Override
        public boolean hasNext() {
            return cusor<N;
        }

        @Override
        public Object next() {
            return eles[cusor++];
        }
    }
}


1.5 顺序表的时间复杂度

get(i):不难看出,不论数据元素量N有多大,只需要一次eles[i]就可以获取到对应的元素,所以时间复杂度为O(1);

insert(int i,T t):每一次插入,都需要把i位置后面的元素移动一次,随着元素数量N的增大,移动的元素也越多,时间复杂为O(n);

remove(int i):每一次删除,都需要把i位置后面的元素移动一次,随着数据量N的增大,移动的元素也越多,时间复杂度为O(n);

由于顺序表的底层由数组实现,数组的长度是固定的,所以在操作的过程中涉及到了容器扩容操作。这样会导致顺序表在使用过程中的时间复杂度不是线性的,在某些需要扩容的结点处,耗时会突增,尤其是元素越多,这个问题越明显


二、链表

之前我们已经使用顺序存储结构实现了线性表,我们会发现虽然顺序表的查询很快,时间复杂度为O(1),但是增删的效率是比较低的,因为每一次增删操作都伴随着大量的数据元素移动。这个问题有没有解决方案呢?有,我们可以使用另外一种存储结构实现线性表,链式存储结构。

链表是一种物理存储单元上非连续、非顺序的存储结构,其物理结构不能只管的表示数据元素的逻辑顺序,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列的结点(链表中的每一个元素称为结点)组成,结点可以在运行时动态生成。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

那我们如何使用链表呢?按照面向对象的思想,我们可以设计一个类,来描述结点这个事物,用一个属性描述这个结点存储的元素,用来另外一个属性描述这个结点的下一个结点。

结点API设计:

类名Node< T >泛型T
构造方法Node(T t,Node next):创建Node对象
成员变量1T item:存储数据
成员变量2Node next:指向下一个结点

点类实现:

public class Node<T> {
	//存储元素
	public T item;
	//指向下一个结点
	public Node next;
	public Node(T item, Node next) {
		this.item = item;
		this.next = next;
	}
}

生成链表:

public static void main(String[] args) throws Exception {
	//构建结点
	Node<Integer> first = new Node<Integer>(11, null);
	Node<Integer> second = new Node<Integer>(13, null);
	Node<Integer> third = new Node<Integer>(12, null);
	Node<Integer> fourth = new Node<Integer>(8, null);
	Node<Integer> fifth = new Node<Integer>(9, null);
	//生成链表
	first.next = second;
	second.next = third;
	third.next = fourth;
	fourth.next = fifth;
}

2.1 单向链表

单向链表是链表的一种,它由多个结点组成,每个结点都由一个数据域和一个指针域组成,数据域用来存储数据指针域用来指向其后继结点。链表的头结点的数据域不存储数据,指针域指向第一个真正存储数据的结点。

在这里插入图片描述

data是数据域,next是指针域
注意:第一个data是null这里称为头节点不存储数据,作用是作为链表的入口帮助我们找到这个链表


2.11单向链表API设计

类名LinkList < T >
构造方法LinkList( ):创建LinkList对象
成员内部类private class Node< T >:结点类
成员变量11.private Node head:记录首结点
成员变量22.private int N:记录链表的长度

成员方法:
1.public void clear():空置线性表
2.publicboolean isEmpty():判断线性表是否为空,是返回true,否返回false
3.public int length():获取线性表中元素的个数
4.public T get(int i):读取并返回线性表中的第i个元素的值
5.public void insert(T t):往线性表中添加一个元素;
6.public void insert(int i,T t):在线性表的第i个元素之前插入一个值为t的数据元素。
7.public T remove(int i):删除并返回线性表中第i个数据元素。
8.public int indexOf(T t):返回线性表中首次出现的指定的数据元素的位序号,若不存在,则
返回-1。


2.12单向链表代码实现

import java.util.Iterator;
public class LinkList<T> implements Iterable<T> {
    //记录头结点
    private Node head;
    //记录链表的长度
    private int N;
    public LinkList(){
//初始化头结点
        head = new Node(null,null);
        N=0;
    }
    //清空链表
    public void clear(){
        head.next=null;
        head.item=null;
        N=0;
    }
    //获取链表的长度
    public int length(){
        return N;
    }
    //判断链表是否为空
    public boolean isEmpty(){
        return N==0;
    }
    //获取指定位置i出的元素
    public T get(int i){
        if (i<0||i>=N){
            throw new RuntimeException("位置不合法!");
        }
        Node n = head.next;
        for (int index = 0; index < i; index++) {
            n = n.next;
        }
        return n.item;
    }
    //向链表中添加元素t
    public void insert(T t){
    //找到最后一个节点
        Node n = head;
        while(n.next!=null){
            n = n.next;
        }
        Node newNode = new Node(t, null);
        n.next = newNode;
    //链表长度+1
        N++;
    }
    //向指定位置i处,添加元素t
    public void insert(int i,T t){
        if (i<0||i>=N){
            throw new RuntimeException("位置不合法!");
        }
    //寻找位置i之前的结点
        Node pre = head;
        for (int index = 0; index <=i-1; index++) {
            pre = pre.next;
        }
    //位置i的结点
        Node curr = pre.next;
    //构建新的结点,让新结点指向位置i的结点
        Node newNode = new Node(t, curr);
    //让之前的结点指向新结点
        pre.next = newNode;
    //长度+1
        N++;
    }
    //删除指定位置i处的元素,并返回被删除的元素
    public T remove(int i){
        if (i<0 || i>=N){
            throw new RuntimeException("位置不合法");
        }
//寻找i之前的元素
        Node pre = head;
        for (int index = 0; index <=i-1; index++) {
            pre = pre.next;
        }
//当前i位置的结点
        Node curr = pre.next;
//前一个结点指向下一个结点,删除当前结点
        pre.next = curr.next;
//长度-1
        N--;
        return curr.item;
    }
    //查找元素t在链表中第一次出现的位置
    public int indexOf(T t){
        Node n = head;
        for (int i = 0;n.next!=null;i++){
            n = n.next;
            if (n.item.equals(t)){
                return i;
            }
        }
        return -1;
    }
    //结点类
    private class Node{
        //存储数据
        T item;
        //下一个结点
        Node next;
        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
    @Override
    public Iterator iterator() {
        return new LIterator();
    }
    private class LIterator implements Iterator<T>{
        private Node n;
        public LIterator() {
            this.n = head;
        }
        @Override
        public boolean hasNext() {
            return n.next!=null;
        }
        @Override
        public T next() {
            n = n.next;
            return n.item;
        }
    }
}




三、栈


四、队列


### Java线性表数据结构算法实验 #### 单链表的实现及其操作 单链表是一种常见的线性表存储方式,其节点由两部分组成:数据域指针域。下面是一个简单的单链表类 `LinkedList` 的实现以及对其增删功能的操作。 ```java class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } public class LinkedList { private Node head; public LinkedList() { this.head = null; } // 插入元素到指定位置 public void addAtPosition(int position, int value) { Node newNode = new Node(value); if (position == 0 || head == null) { newNode.next = head; head = newNode; return; } Node current = head; for (int i = 0; i < position - 1 && current != null; i++) { current = current.next; } if (current != null) { newNode.next = current.next; current.next = newNode; } } // 删除指定位置的元素 public void removeAtPosition(int position) { if (head == null) return; if (position == 0) { head = head.next; return; } Node current = head; for (int i = 0; i < position - 1 && current != null; i++) { current = current.next; } if (current != null && current.next != null) { current.next = current.next.next; } } // 遍历并打印链表中的所有元素 public void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } } ``` 上述代码实现了单链表的基本操作,包括向特定位置插入新节点[^4] 删除指定位置上的节点[^5]。通过调用这些方法可以完成对单链表的各种修改需求。 #### 测试样例解释 以下是对测试样例的具体说明: ```java public static void main(String[] args) { LinkedList list = new LinkedList(); list.addAtPosition(0, 3); // 向索引为0的位置添加数值3 list.addAtPosition(1, 5); // 向索引为1的位置添加数值5 list.addAtPosition(2, 7); // 向索引为2的位置添加数值7 list.addAtPosition(3, -1); // 向索引为3的位置添加数值-1 list.addAtPosition(2, 4); // 向索引为2的位置添加数值4 list.addAtPosition(0, -6); // 向索引为0的位置添加数值-6 list.removeAtPosition(0); // 移除索引为0处的元素 list.printList(); // 输出最终的结果 } ``` 运行以上程序会依次执行一系列增加移除操作,并最后输出剩余列表的内容。此过程展示了如何动态调整单链表内的目顺序[^6]。 #### 关于栈的功能扩展 除了单链表外,在某些情况下还需要了解其他形式的线性表应用实例——比如堆栈(Stack),它遵循后进先出(LIFO)原则。这里给出一个基于数组实现的简单版本: ```java import java.util.EmptyStackException; public class ArrayStack<E> { private E[] arr; private int size; @SuppressWarnings("unchecked") public ArrayStack(int capacity){ arr=(E[])new Object[capacity]; size=0; } public boolean isEmpty(){ return size==0; } public void push(E item)throws Exception{ if(size>=arr.length){ throw new Exception("The stack is full"); } arr[size++]=item; } public E pop()throws EmptyStackException{ if(isEmpty()){ throw new EmptyStackException(); } E result=arr[--size]; arr[size]=null;//帮助垃圾回收器工作 return result; } public int getSize(){ return size; } public String toString(){ StringBuilder sb=new StringBuilder("["); for(int i=size-1;i>=0;i--){ sb.append(arr[i]); if(i!=0)sb.append(","); } sb.append("]"); return sb.toString(); } } ``` 该段代码提供了基本的压栈(push), 出栈(pop)[^7], 判断是否为空(isEmpty()), 获取当前容量(getSize())等功能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值