算法之如何实现线性表的顺序存储?(Java)

本文介绍使用Java实现线性表的顺序存储方法,重点讲解了数组扩容、元素的插入与删除等关键操作,并提供了完整的代码示例及运行结果。

Java实现线性表的顺序存储







1.基本思路

1.基本数据的算法实现基本包括四个最重要的功能:增、删、改、查
2.在这个例子中,我是用数组来实现线性表的顺序存储。如果数组空间不够,那就要扩大数组。
3.线性表在数组内进行存储,主要参数有三个:数组arrs,数组长度maxSize,线性表List长度size



2.实际功能列表

![实际功能列表](https://img-blog.youkuaiyun.com/20180426140848184?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JhaWR1XzM0MTIyMzI0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
![实际功能列表](https://img-blog.youkuaiyun.com/20180426140905217?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JhaWR1XzM0MTIyMzI0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)


##3.代码块 ###3.1要点 ####3.1.1扩大数组: 首先要创建一个更大的数组,然后把arrs通过中介数组oldarrs传递到新的大数组newarrs里面去。
if ((size == maxSize)){
            //Expand the size
            int[] oldarrs;
            int[] newarrs;
            oldarrs = arrs;
            newarrs = new int[maxSize * 2];
            for (int j = 0; j < size; j++) {
                newarrs[j] = oldarrs[j];
            }
            maxSize = maxSize * 2;
            arrs = newarrs;
        }

####3.1.2插入功能(增)
1.如果线性表的size已满(size == maxSize),就要扩大数组(详见3.1.1)
2.判断i是否超出范围((i < 1) || (i > (size+1)))
3.分两种情况进行插入:插入中部和插入尾部

public void add(int i, int e){
        if ( (i < 1) || (i > (size+1)) ){
            throw new IllegalArgumentException(" The i is out of bound!");
        }
        if ((size == maxSize)){
            //Expand the size
            int[] oldarrs;
            int[] newarrs;
            oldarrs = arrs;
            newarrs = new int[maxSize * 2];
            for (int j = 0; j < size; j++) {
                newarrs[j] = oldarrs[j];
            }
            maxSize = maxSize * 2;
            arrs = newarrs;
        }
        if (i <= size){
            for (int j = size - 1; j >= i - 1; j--) {
                arrs[j + 1] = arrs[j];
            }
        }

        arrs[i-1] = e;
        size++;
        display();
    }

####3.1.3删除功能(删):
1.判断线性表是否为空(size == 0)
2.判断i是否超出范围(i < 1 || i > size)
3.分两种情况进行删除:删除中部和删除尾部

    public void remove(int i){
        if (size == 0){
            throw new IllegalArgumentException(" Sorry, the List is null!");
        }
        if (i < 1 || i > size){
            throw new IllegalArgumentException(" Sorry, the index is out of bound!");
        }
        if (i < size){
            for (int j = i; j < size; j++) {
                arrs[j - 1] = arrs[j];
            }
        }
        size--;
        display();
    }

###3.2基本功能 ```Java

public class LinearList {
//Create a new array
private int[] arrs;

//The default size
public static final int DEFAULT_SIZE = 10;

//The array's size
private int maxSize;

//The List size
private int size;

/*
Two method to initialize the List
1.Default Size
2.Using the appointed size
 */
public LinearList(){
    this(DEFAULT_SIZE);
}

public LinearList(int size){
    maxSize = size;
    arrs = new int[maxSize];
}

//Determine if the List is empty
public boolean isEmpty(){
    if (size == 0){
        System.out.println(" The List is empty!");
        return true;
    }else {
        return false;
    }
}

//Get the length of the List
public int getLength(){
    return size;
}

//Get the appointed element
public int getElement(int i){
    if ((size == 0) || (i < 1) || (i > size)){
        throw new IllegalArgumentException(" The i is out of bound!");
    }
    return arrs[i-1];
}

public void LocateElement(int e){
    for (int i = 0; i < size; i++) {
        if (arrs[i] == e){
            System.out.println(" Existing in the " + " index.");
            break;
        }
        if (size == i+1){
            System.out.println(" The element is not existent.");
        }
    }
}

/*
Insert the element e into the ith filed of the List
1.Determine if the index i is out of bound
2.if the size is out of bound, expanding the List Size
3.Divide two situation when you wanna insert element
    ->between the List
    ->into the end of the List
 */
public void add(int i, int e){
    if ( (i < 1) || (i > (size+1)) ){
        throw new IllegalArgumentException(" The i is out of bound!");
    }
    if ((size == maxSize)){
        //Expand the size
        int[] oldarrs;
        int[] newarrs;
        oldarrs = arrs;
        newarrs = new int[maxSize * 2];
        for (int j = 0; j < size; j++) {
            newarrs[j] = oldarrs[j];
        }
        maxSize = maxSize * 2;
        arrs = newarrs;
    }
    if (i <= size){
        for (int j = size - 1; j >= i - 1; j--) {
            arrs[j + 1] = arrs[j];
        }
    }

    arrs[i-1] = e;
    size++;
    display();
}

/*
Remove the element e from the index i of the List
1.Determine if the index i is out of bound, Determine if the size is 0
2.Remove the element from the List
3.Divide two situation when you wanna remove element
    ->between the List
    ->on the end of the List
 */
public void remove(int i){
    if (size == 0){
        throw new IllegalArgumentException(" Sorry, the List is null!");
    }
    if (i < 1 || i > size){
        throw new IllegalArgumentException(" Sorry, the index is out of bound!");
    }
    if (i < size){
        for (int j = i; j < size; j++) {
            arrs[j - 1] = arrs[j];
        }
    }
    size--;
    display();

}

//Clear the List
public void removeAll() {
    if(arrs != null){
        for (int i = 0; i < size; i++) {
            arrs[i] = 0;
        }
    }
    size = 0;
    System.out.println(" Clear completed!");
    display();
}


//display the List
public void display(){
    if (arrs != null){
        System.out.println("");
        for (int i = 0; i < size; i++) {
            System.out.print(" " + arrs[i]);
        }
    }
}

}

<br>
###3.3测试代码

```Java

public static void main(String[] args) {
        LinearList linearList = new LinearList(5);
        linearList.add(1,1);
        linearList.add(2,2);
        linearList.add(1,3);
        linearList.add(1,4);
        linearList.add(1,5);
        linearList.add(1,6);
        System.out.println();

        linearList.remove(1);
        linearList.remove(5);
        System.out.println();
        System.out.println();

        linearList.LocateElement(3);
        linearList.LocateElement(2);
        System.out.println();

        linearList.removeAll();
    }

###3.4输出示例
![输出示例](https://img-blog.youkuaiyun.com/20180426141648477?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JhaWR1XzM0MTIyMzI0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)


##4.线性表顺序存储的优缺点 优点 | 缺点 - | - 无须为表示表中元素之间的逻辑关系而增加额外的存储空间 | 插入和删除操作需要移动大量的元素 可以快速地存取表中任一位置的元素 | 当线性表长度变化较大时,难以确定存储空间的容量 . | 造成存储空间的碎片
### Java 实现线性表顺序查找算法Java中,针对不同类型的线性表(如`ArrayList`或自定义的链表),可以实现顺序查找算法。下面分别展示基于数组列表和链表这两种常见线性表结构下的顺序查找方法。 #### 基于 ArrayList 的顺序查找 由于`ArrayList`内部是以数组形式存储元素,在这种情况下执行顺序查找非常直观: ```java import java.util.ArrayList; import java.util.Arrays; public class ArrayLinearSearch { public static boolean sequentialSearch(ArrayList<Integer> list, int target){ for (Integer element : list) { if(element.equals(target)){ return true; } } return false; } public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 3, 5, 7, 9, 11, 13, 15)); System.out.println("Is 7 present? " + sequentialSearch(numbers, 7)); // 输出: Is 7 present? true System.out.println("Is 8 present? " + sequentialSearch(numbers, 8)); // 输出: Is 8 present? false } } ``` 此代码片段展示了如何创建一个整数型的`ArrayList`并对其进行顺序查找[^1]。 #### 自定义单向链表上的顺序查找 当处理由节点组成的链表时,则需逐个访问每个节点直到找到目标值为止: ```java class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } public class LinkedListSequentialSearch { private Node head; public LinkedListSequentialSearch() { head = null; } /** * 向链表尾部添加新节点. */ public void addLast(int value) { Node newNode = new Node(value); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } } /** * 对链表进行顺序查找. */ public boolean search(int key) { Node temp = head; while (temp != null && !temp.data.equals(key)) { temp = temp.next; } return temp != null; } public static void main(String[] args) { LinkedListSequentialSearch linkedList = new LinkedListSequentialSearch(); linkedList.addLast(1); linkedList.addLast(3); linkedList.addLast(5); System.out.println("Does the list contain '3'? " + linkedList.search(3)); // 应该返回true System.out.println("Does the list contain '4'? " + linkedList.search(4)); // 应该返回false } } ``` 这段程序首先构建了一个简单的单项链表类及其基本功能——添加元素到链表末端以及按照给定键值进行顺序查找的功能[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值