单链表的简单实现

**

单链表的简单实现

**在这里插入图片描述

package com.atguigu.javase.homeworl;


class Note {
	int value;
	Note nextNote;  //作为向下指针

	public Note(int value) {
		this.value = value;
	}

}

public class Link {
	private Note head;// 首地址
	private Note tail;// 尾部地址

	public Note getHead() {
		return head;
	}

	public Note getTail() {
		return tail;
	}

	// 尾部增加单链表的方法
	public void add(int value) { //在尾部插入
		Note newNote = new Note(value);
		if (head == null) {//判断是否存在链表
			head = newNote;
			tail = newNote;
		} else { //如果存在则进行连接并且刷新尾部地址
			tail.nextNote = newNote;
			tail = tail.nextNote;
		}
	}

	public void add(int value, int valu1) {// 在此value值后插入 value1
		if (head == null) {//判断是否有数据
			System.out.println("没有数据");
		} else {
			Note tmp = head;
			while (tmp.value != value) {//当找到此value时跳出循环
				tmp = tmp.nextNote;
				if (tmp == null) {// 表示到达链表尾部也未找到  也跳出当前循环
					System.out.println("没有数据");
					return;
				}
			}

			Note exchange = tmp.nextNote;
			Note addNote = new Note(valu1);
															//确定插入位置 改变相应的nextNote指向
			tmp.nextNote = addNote; 
			addNote.nextNote = exchange;
		}

	}

	public void delet(int value) {
		if (head == null) {
			System.out.println("没有数据");
		} else {
			if(head.value == value) {//删除头
				
				head = head.nextNote;
				
			}
			Note tmp2 = head;
			if(tmp2.nextNote==null) { //判断head后时都还有数据
				System.out.println("无此数据");
				return;
			}
			while (tmp2.nextNote.value != value) {//确定删除的是下一个Note
			if(	tmp2.nextNote.nextNote==null) {   
				System.out.println("无此数据");
				return;
			}
				tmp2 = tmp2.nextNote;
				
			}
			Note tmp3 = tmp2.nextNote.nextNote;
			tmp2.nextNote = tmp3;
		}
	}

	public void toSay() {             //遍历链表的value数据
		if (head == null) {
			System.out.println("未存任何数据");
			return;
		}
		Note note = head;
		while (note != null) {
			System.out.println(note.value);
			note = note.nextNote;
		}

	}
	public int[] toArray() {//封装一个返回数组的链表方法  也可以在该类中定义一个计数器 在add方法和delete方法里完成增减
		Note note = head;
		int account = 0;//用于统计数据的个数即链表的长度
		while (note != null) {
			//System.out.println(note.value);
			account++;
			note = note.nextNote;
		}
		System.out.println(account);
		int[] arr = new int[account];//创建数组用于接收链表的数据
		int i = 0;
		while (note != null) {  //遍历链表数据依次写入数组
			arr[i] = note.value;
			i++;
			note = note.nextNote;
		}
		return arr;
	}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值