博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
简单实现一个数组、链表
阅读量:3966 次
发布时间:2019-05-24

本文共 2200 字,大约阅读时间需要 7 分钟。

简单实现一个数组、链表

数组

  • 实现一个数组
public class Array {
private int[] arr = new int[12];//数组大小为12 private int flag = 0;//标志变量 public void add(int x) {
//添加数据 arr[flag] = x; flag++; } public void show() {
//遍历输出数组中的所有数据 for(int i = 0; i < flag; i++) {
System.out.println("数组:"+arr[i]); } } public void check(int x) {
//查找数组中是否有该数据 for(int i = 0; i < flag; i++) {
if( arr[i] == x ) {
System.out.println("有这个数据"); return;//退出 } } System.out.println("不存在这个数据"); } public void delete(int x) {
//删除数组中的特定值 for(int i = 0; i < flag; i++) {
if( arr[i] == x ) {
for(int k = i+1; k < flag; k++) {
//计算机里面的删除是把数据标记为无效或者覆盖 arr[k-1] = arr[k]; } flag--; System.out.println("删除成功"); return;//退出 } } }}
  • 测试类
public class Test {
public static void main(String[] args) {
Array array = new Array();//数组大小为12 array.add(1); array.add(2); array.add(3); array.add(4); array.add(5); array.show(); array.check(2); array.delete(1); array.show(); }}
  • 输出结果

数组:1 2 3 4 5

有这个数据
删除成功
数组:2 3 4 5

链表(单链表)

  • 声明Node类
public class Node {
public int value; public Node next; //重写toString方法 @Override public String toString() {
return "Node [value=" + value + ", next=" + next + "]"; }}
  • 创建Test类实现单链表的创建和反转
public class Test {
public static void main(String [] args) {
int[] arr = {
34,32,12,2,45,65,77,36}; //用arr数组建立单链表 Node link = null; for(int i = 0; i < arr.length; i++) {
Node no = new Node();//方法执行完自动回收 no.value = arr[i]; no.next = link; link = no; } //反转前 System.out.println("反转前:" + link); //实现单链表的反转 Node link2 = null; while(link != null) {
Node no = link; link = link.next; no.next = link2; link2 = no; } //反转后 System.out.println("反转后:" + link2); }}
  • 输出结果
反转前:Node [value=36, next=Node [value=77, next=Node [value=65, next=Node [value=45, next=Node [value=2, next=Node [value=12, next=Node [value=32, next=Node [value=34, next=null]]]]]]]]反转后:Node [value=34, next=Node [value=32, next=Node [value=12, next=Node [value=2, next=Node [value=45, next=Node [value=65, next=Node [value=77, next=Node [value=36, next=null]]]]]]]]

转载地址:http://fsyki.baihongyu.com/

你可能感兴趣的文章
Zedboard中的SPI通信记录文档(已实现)
查看>>
zigbee学习笔记2----cc2530 IO实验
查看>>
zigbee学习笔记4----初次接触zstack
查看>>
Android 发布到google Play的app搜索不到问题的解决
查看>>
Flutter 网络请求之基于dio的简单封装
查看>>
Flutter UI基础 - 路由之Navigator详解
查看>>
Flutter UI基础 - Widgets 之 InkWell 和 Ink
查看>>
Spring - sentinel和hystrix比较
查看>>
MySQL - 索引之B+树
查看>>
Spring - Dubbo的底层实现原理和机制
查看>>
Flutter Dio引入和简单的Get/Post请求
查看>>
Flutter Dart 和 Flutter json转实体类(插件自动生成)
查看>>
Flutter 路由跳转fluro
查看>>
Flutter 日期插件date_format 中文 国际化 及flutter_cupertino_date_picker
查看>>
Flutter 插件笔记 | 屏幕适配 flutter_screenutil
查看>>
Flutter UI基础 - 侧拉抽屉菜单
查看>>
Flutter UI基础 - AppBar中标题文字如何居中
查看>>
Flutter UI基础 - Drawer 抽屉视图与自定义header
查看>>
Flutter UI基础 - 点击展开和关闭
查看>>
Flutter UI基础 - GridView
查看>>