Java练习数据结构第2章线性表——单链表

2.3.1 单链表 P24

package hicc.ds.c02_linear;

class LNode {
	Object data;
	LNode next;
	public LNode(Object data) {
		this.data = data;
		this.next = null;
	}
}

public class LinkList {
	private LNode H; //链表头结点
	private LNode L; //链表尾结点
	
	public LinkList() {
		H = L = null;
	}
	
	public LNode get(int i) { //按索引查找
		LNode p = H;
		int j = 0;
		while (p != null && p.next != null && j < i) {
			p = p.next;
			j++;
		}
		return p;
	}
	
	public LNode location(Object x) { //按值查找
		LNode p = H;
		while (p != null && !p.data.equals(x)) {
			p = p.next;
		}
		return p;
	}
	
	public void insert(Object x) { //添加数据
		LNode n = new LNode(x);
		if (H == null) {
			H = L = n;
		} else {
			L.next = n;
			L = n;
		}
	}
	
	public int insert(int i, Object x) { //向指定位置添加数据
		LNode p = get(i);
		if (p == null) {
			return -1;
		} else {
			LNode n = new LNode(x);
			n.next = p.next;
			p.next = n;
			Object temp = n.data;
			n.data = p.data;
			p.data = temp;
			return 1;
		}
	}
	
	public int delete(int i) { //删除运算
		LNode p = get(i-1);
		if (p == null) {
			return -1; //
		} else {
			if (p.next == null) { 
				return 0; //
			} else {
				LNode n = p.next;
				p.next = n.next;
				return 1;
			}
		}
	}
	
	public void showData() { //展示链表数据
		LNode p = H;
		if (p == null) {
			System.out.println("null");;
		} else {
			while (p != null) {
				System.out.print(p);
				System.out.print('|');
				System.out.print(p.data);
				System.out.print('|');
				System.out.println(p.next);
				p = p.next;
			}
		}
	}

	public static void main(String[] args) {
		LinkList linkList = new LinkList();
		linkList.insert('A');
		linkList.insert('B');
		linkList.insert('C');
		linkList.showData();
		System.out.println(linkList.get(1));
		System.out.println(linkList.location('C'));
		linkList.insert(2, 'D');
		linkList.showData();
		linkList.delete(2);
		linkList.showData();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值