线性表顺序存储

package com.ct.test;

public class ArrayListTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		SLType s = new SLType();
		Data d = new Data();
		d.key = "one";
		d.name = "ct";
		d.age = 20;
		Data d1 = new Data();
		d1.key = "two";
		d1.name = "xx";
		d1.age = 30;

		s.add(s, d);
		s.add(s, d1);
		s.FindByKey(s, "one");

	}

}

class Data { // 数据结点类型
	String key;
	String name;
	int age;
}

class SLType {
	static final int MaxLen = 100;// 定义顺序表结构
	Data[] ListData = new Data[MaxLen + 1];
	int ListLen = 0;// 顺序表已存节点数量
	Data temp;
	Data data;

	public void SLInit(SLType SL) { // 初始化空表
		SL.ListLen = 0;
	}

	public int SLLength(SLType SL) {// 返回顺序表的元素量

		return SL.ListLen;
	}

	// 插入数据
	public int ini(SLType SL, int n, Data data) {
		int i;
		// 判断插入位置是否合法
		if (SL.ListLen > MaxLen) {
			System.out.println("顺序表已满,不能插入元素!");
			return 0;// ?
		}
		if (n < 1 || n > SL.ListLen - 1) {
			System.out.println("插入数据位置错误,不能插入元素.");
			return 0;
		}
		for (i = SL.ListLen; i >= n; i--) {
			SL.ListData[i + 1] = SL.ListData[i];

		}

		SL.ListData[n] = data;
		SL.ListLen++;
		return 1;
	}

	// 增加元素到表尾
	public int add(SLType SL, Data data) {
		if (SL.ListLen >= MaxLen) {
			System.out.println("循序表已满,不能添加!");
			return 0;
		}

		SL.ListData[SL.ListLen++] = data;// 先自增1,再在增加的位置添加
		// SL.ListLen++;
		return 1;
	}

	// 删除元素
	public Data del(SLType sl, int n) {

		if (n > sl.ListLen || n < 0) {
			System.out.println("删除位置不合适");
			return null;
		}

		for (int i = 0; i <= sl.ListLen; i++) {
			if (i == n) {
				temp = sl.ListData[i];
				sl.ListData[i] = sl.ListData[i + 1];
				sl.ListLen--;
			}
		}
		return temp;
	}

	// 根据序号返回数据
	public Data FindByNum(SLType sl, int n) {
		int i = 0;
		if (n > sl.ListLen || n < 0) {
			System.out.println("查找位置不对,请检查!");
			return null;
		}
		while (i <= n) {
			data = sl.ListData[i];
			i++;
		}

		return data;
	}

	// 按关键字查找
	public void FindByKey(SLType s, String key) {
		for (int i = 0; i < s.ListLen; i++) {
			if (s.ListData[i].key.equals(key)) {

				System.out.println("key:" + s.ListData[i].key + "\n" + "name:"
						+ s.ListData[i].name + "\n" +"age:"+ s.ListData[i].age);
				return ;
			}
			else{
				System.out.println("找不到");
			}
		}

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值