单向链表SingleLink

1.实现单向链表

在这里插入图片描述

public class SingleLink {
	private Node head;
	private int size;
	
	private class Node{
		private Object data;
		private Node next;
		
		public Node(Object data) {
			this.data = data;
		}
	}
	
	public SingleLink() {
		// TODO Auto-generated constructor stub
		head = null;
		size = 0;
	}
	
	public Object addHead(Object obj) {
		Node node = new Node(obj);
		if(size==0) {
			head = node;
		}else {
			node.next=head;
			head = node;
		}
		size++;
		return obj;
	}
	
	public Object add(Object obj) {
		Node node = new Node(obj);
		if(size==0) {
			head = node;
		}else {
			head.next = node;
		}
		size++;
		return obj;
	}
	
	public Object removeHead() {
		Object obj = head.data;
		if(size==0) {
			throw new IndexOutOfBoundsException();
		}else if(size==1){
			head = null;
		}else {
			head = head.next;
		}
		size--;
		return obj;
	}
	
	public Node findData(Object obj) {
		Node current = head;
		for(int i=0;i<size;i++) {
			if(current.data==obj) {
				return current;
			}else {
				current = current.next;
			}
		}
		return null;
	}
	
	public boolean removeData(Object obj) {
		Node current = head;
		Node previous = head;
		if(size==0) {
			return false;
		}
		
		while(current.data !=obj) {
			if(current.next ==null) {
				return false;
			}else {
				previous = current;
				current = current.next;
			}
		}
		
		if(current==head) {
			head = current.next;
			size--;
		}else {
			previous.next = current.next;
			current.next = null;
			size--;
		}
		
		return true;
	}
	
	public boolean isEmpty() {
		return (size==0);
	}
	
	public void display() {
		if(size>0) {
			Node node = head;
			int tempSize =size;
			
			if(size==1) {
				System.out.println("["+node.data+"]");
				return;
			}
			
			while(tempSize>0) {
				if(node==head) {
					System.out.print("["+node.data+"->");
				}else if(node.next ==null) {
					System.out.print(node.data+"]");
				}else {
					System.out.print(node.data+"->");
				}
				node = node.next;
				tempSize--;
			}
			System.out.println();
		}else {
			System.out.println("[]");
		}
		
	}
	
}

2.使用

public class SingleList {
	public static void main(String[] args) {
		SingleLink link = new SingleLink();
		link.addHead("aaa");
		link.display();
		
		link.add("bbb");
		link.display();
		
		link.addHead("ccc");
		link.display();
		
		link.removeHead();
		link.display();
		
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值