本文共 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
public class Node { public int value; public Node next; //重写toString方法 @Override public String toString() { return "Node [value=" + value + ", next=" + next + "]"; }}
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/