单链表实现

本文介绍了一个简单的单链表实现,包括添加、删除、查找等基本操作,并提供了完整的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.zi.test;


public class SingleLinkList {
	
	/**
	 * define a class Value for using object of Element
	 * @author Administrator
	 *
	 */
	class Value {
		
	}
	
	class Element {
		Object value = null;
		Element nextNode = null;
	}
	
	private Element header = null;
	
	/**
	 * every time, add a node into front position in linklist.
	 * header is null object, it is for mark nextNode.
	 * insertNode is for add into linklist.
	 * 
	 * 
	 * [header[value|nextNode]]---->[oneNode[value|nextNode]]
	 *                          ^
	 *                          |
	 *               insertNode[value|nextNode]
	 * 
	 */
	public void add(Object node) {
		if(header == null) {
			header = new Element();
			header.value = null;
			header.nextNode = null;
		}
		
		Element insertNode = new Element();
		insertNode.value = node;
		insertNode.nextNode = header.nextNode;
		header.nextNode = insertNode;
	}
	
	/**
	 * header is null, so the linklist has not mark node, that the linklist is null
	 */
	public void clear() {
		header = null;
	}
	
	/**
	 * compare node from header node to end node.
	 * @param node
	 * @return
	 */
	public boolean contain(Object node) {
		if (header == null) return false;
		
		Element eqEl = header.nextNode;
		while (eqEl != null) {
			if (eqEl.value == node) return true;
			eqEl = eqEl.nextNode;
		}
		
		return false;
	}
	
	/**
	 * scan total linklist for getting the size
	 * @return
	 */
	public int size() {
		if (header == null) return 0;
		
		int i = 0;
		Element ele = header.nextNode;
		while(ele != null) {
			i++;
			ele = ele.nextNode;
		}
		return i;
	}
	
	/**
	 * scan total linklist for getObject by index
	 * @param index
	 * @return
	 */
	public Object getObject(int index) {
		if (header == null) return null;
		int size = this.size();
		if (index > size -1 || index < 0) return null;
		
		int i = 0;
		Element ele = header.nextNode;
		while (ele != null) {
			if (i == 0) return ele.value;
			i++;
			ele = ele.nextNode;
		}
		
		return null;
	}
	
	public boolean remove(Object node) {
		if (header == null) return false;
		Element eqPreEl = header;
		Element eqEl = header.nextNode;
		while (eqEl != null) {
			if (eqEl == node) {
				eqPreEl.nextNode = eqEl.nextNode;
				return true;
			}
			eqPreEl = eqEl;
			eqEl = eqEl.nextNode;
		}
		return false;
	}
	
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值