java数据结构之单链表的实现

本文介绍了一种使用Java实现单链表的方法,包括初始化、插入、删除元素等核心功能,并提供了完整的代码示例。

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

借鉴http://www.cnblogs.com/lixiaolun/p/4643886.html思路

初始化单链表,采用尾插法插入元素,打印该链表

采用相同的思路对链表进行了删除、获取链表长度、获取链表的第i个元素以及判断某元素是否存在该链表中等操作

public class LinkList {

	class Element{//结点
		public Object value = null ;
		private Element next = null;
	}
	private Element head = null;//头结点
	
	//初始化链表
	void initList(){
		head = new Element();
		head.value = null ;
		head.next = null ;
	}
	
	//尾插法  插入元素
	void insert(Object o){
		Element e = new Element() ;//一个新结点
		e.value = o ;
		if( head.next == null ){//第一次插入
			head.next = e ;
		}else{
			Element temp = head ;//temp指向head这个头结点
			while(temp.next!=null){
				temp = temp.next ;//temp指向当前结点,令temp指向下一个结点
			}
			temp.next = e ;//当temp指向最后一个结点时,temp.next为null,此时令其等于e这个结点
		}
	}
	
	//删除元素
	
	void delete(Object o){
		Element temp = head ;
		int i = 0 ;
		while( temp.next != null ){
			if(temp.next.value.equals(o)){
				temp.next = temp.next.next ;
				System.out.println("您删除了链表中的"+o+"元素");
				i++;//做一个标记,如果没有变化则表示没有进入到if语句中,所以表示没有该元素存在
			}else {
				temp = temp.next ;
			}
		}
		if( i == 0 ){//一个问题,提示要删除的元素不存在
			System.out.println("您要删除的元素"+o+"不存在");
		}
		
	}
	
	//获取链表的长度
	public int getLe(){
		int i = 0 ;
		Element temp = head ;
		while(temp.next != null ){
			i++;
			temp = temp.next ;
		}
		return i;
	}
	
	//获取该链表的第i个元素
	public Element getElement(int i){
		if(i <= 0 || i > getLe()){
			System.out.println("获取链表的位置有误!");
			return null ;
		}else{
			Element temp = head ;
			for(int j = 0 ; j < i ;j++ ){
				temp = temp.next ;
			}
			return temp;
		}
	}
	
	//判断某元素是否存在
	public void isContain(Object o) {
		Element temp = head ;
		int i=0 ;
		while( temp.next != null){
			if(temp.next.value.equals(o)){
				i++;//记次数,出现过几次
			}
			temp = temp.next ;
		}
		if( i == 0 ){
			System.out.println("该链表中不存在元素"+o);
		}else {
			System.out.println("该链表中存在"+o+"元素,且出现"+i+"次");
		}
	}
	
	//打印链表
	void print(){
		System.out.println("打印链表:");
		Element temp = head ;
		if( temp.next == null ){
			System.out.println("该链表为空");
		}
		while( temp.next != null ){
			temp = temp.next ;
			System.out.print(temp.value + "\t");
		}
		System.out.println("");
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkList list = new LinkList();
		list.initList();
		list.insert(1);
		list.insert(2);
		list.insert(3);
		list.insert(4);
		list.insert(5);
		list.insert(5);
		list.insert(3);
		list.insert(4);
		list.print();
//		System.out.println("该链表的长度是"+list.getLe());
//		list.delete(5);
//		list.print();
//		System.out.println("该链表的长度是"+list.getLe());
		//System.out.println("该链表第2个元素是"+list.getElement(2).value);
		list.isContain(5);
		list.isContain(0);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值