数据结构
什么是数据结构?
数据结构时描述和组织数据的方式 数据+结构
数据结构是一门逻辑非常严谨的学科,插入数据的时候:1.判空 2.数据合法性判断 3. 插入数据的时候,这个位置之前一定要有数据
为什么数据结构那么多,主要是因为描述和组织数据的方式不一样
主要有:队列,顺序表(底层实际上是一个数组)
如何学好数据结构?
1.画图
2.多写代码
顺序表的代码实现
import java.util.Arrays;
public class MyArrayList {
private int[]elem;//null
private int usedSize;
public MyArrayList(){
this.elem = new int[10];//无参构造方法
}
public MyArrayList(int capacity){
this.elem = new int[capacity];//有参的构造方法
}
// 打印顺序表
public void display(){
for(int i =0;i<this.usedSize;i++){
System.out.println(this.elem[i] );
}
}
public boolean isFull(){
if(this.usedSize == this.elem.length){
return true;
}
return false;
}
public void resize(){
this.elem =
Arrays.copyOf(this.elem,2*this.elem.length);
}
// 在 pos 位置新增元素
public void add(int pos, int data){
//顺序表是否为满
if(isFull()){
//System.out.println("顺序表为满!")
resize();
}
//pos是否合法
if(pos<0||pos>this.usedSize){
System.out.println("pos位置不合法");
return;
}
//移动元素
for(int i =this.usedSize-1;i>=pos;i--){
this.elem[i+1]=this.elem[i];
}
this.elem[pos] = data;
this.usedSize++;
}
//默认插入到数组最后
public void add2(int data){
//顺序表是否为满
if(isFull()){
//System.out.println("顺序表为满!")
resize();
}
this.elem[this.usedSize] = data;
this.usedSize++;
}
// 判定是否包含某个元素
public boolean contains(int toFind) {
for(int i = 0;i<this.usedSize;i++){
if(toFind==this.elem[i]){
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int search(int toFind) {
for(int i = 0;i<this.usedSize;i++){
if(toFind==this.elem[i]){
return i;
}
}
return -1;
}
// 获取顺序表长度
public int size() {
return this.usedSize;
}
// 获取 pos 位置的元素
public int getPos(int pos) {
if(pos<0||pos>=this.usedSize){
return-1;
}
return -1;
}
// 给 pos 位置的元素设为 value
public void setPos(int pos, int value){
if(pos<0||pos>=this.usedSize){
return;
}
this.elem[pos] = value;
}
//删除第一次出现的关键字key
public void remove(int key){
//1.查找是否有2 index
int index = search(key);
if(index==-1){
System.out.println("没有该元素");
return;
}
//2. i=index i<usedSize-1
for(int i =index;i<this.usedSize-1;i++){
this.elem[i]=this.elem[i-1];
}
//this.usedSize--;
this.usedSize--;
}
// 清空顺序表
public void clear(){
this.usedSize = 0;
}
}