用java实现的自定义单向链表

package com.hebtu.java.list;

/**
 * 链表节点
 * @author Xmh
 *
 */
public class Link {
	private int num;

	private Link next; //指向下一个节点

	public Link() {
		super();
	}

	public Link(int num) {
		super();
		this.num = num;
	}
	
	public void displayLink(){
		System.out.println("num: " + num);
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public Link getNext() {
		return next;
	}

	public void setNext(Link next) {
		this.next = next;
	}
	
	public static void main(String[] args) {
		MyList list = new MyList();
		//插入数据
		list.insert(2);
		list.insert(4);
		list.insert(6);
		list.insert(8);
		//打印链表
		list.displayList();
		
		//链表不为空,删除数据
		while(!list.isEmpty()){
			Link removeFirst = list.removeFirst();
			System.out.println("Delete....");
			removeFirst.displayLink();
		}
		
		list.displayList();
	}
}

/**
 * MyList: 自定义的单向链表,支持表头插入和表头删除操作
 * @author Xmh
 *
 */
class MyList{
	private Link first; //指向第一个节点对象的引用
	
	/**
	 * 构造器:初始化空链表,让 first引用指向 null(默认就是指向 null 的)
	 */
	public MyList() {
		first = null;
	}
	
	/**
	 * 往链表中插入数据:只在表头插入
	 * @param num
	 */
	public void insert(int num){
		// 1.先创建一个节点对象
		Link newLink = new Link(num);
		// 2.1 新对象 的 next 引用,指向 first
		newLink.setNext(first);
		// 2.2 让first指向新插入的对象
		first = newLink;
	}
	
	/**
	 * 从链表中移除头结点,并且返回之。
	 * @return
	 */
	public Link removeFirst(){
		Link temp = first; //首先保存第一个节点的引用,即要输出的节点
		// first--->old next(将first引用指向下下个节点对象)
		first = first.getNext();
		return temp;
	}
	
	/**
	 * 打印链表
	 */
	public void displayList(){
		System.out.println("List(first--->last)...");
		Link current = first; // 链表的开始节点引用
		while(current != null){
			current.displayLink();
			//指向下一个节点
			current = current.getNext();
		}
		System.out.println("");
	}
	
	/**
	 * 判断链表是否为空
	 * @return
	 */
	public boolean isEmpty(){
		if(first==null){
			return true;
		}else{
			return false;
		}
	}
	
}
控制台打印结果:
List(first--->last)...
num: 8
num: 6
num: 4
num: 2


Delete....
num: 8
Delete....
num: 6
Delete....
num: 4
Delete....
num: 2
List(first--->last)...
 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值