java简单链表

public class LinkedList<T> {
	Node<T> headNode = null;
	Node<T> tailNode = null;
	int count = 0;
	public LinkedList() {
		// TODO Auto-generated constructor stub
		tailNode = headNode =  new Node<T>();
		headNode.element = null ;
	}
	void insertAtHead(T element) {
		Node<T> tempNode = new Node<>();
		tempNode.element = element;
		tempNode.next = headNode.next;
		headNode.next = tempNode;
		if (count == 0) {
			tailNode = tempNode;
		}
		count++;
	}
	void insertAtTail(T element) {
		Node<T> tempNode = new Node<>();
		tempNode.element = element;
		tempNode.next = null;
		tailNode.next = tempNode;
		tailNode = tempNode;
		count++;
	}
	static void display(LinkedList<?> linkedList) {
		if (linkedList.count != 0) {
			Node<?> iteratorNode = linkedList.headNode.next;
			while(iteratorNode!=null) {
				System.out.println(iteratorNode.element);
				iteratorNode = iteratorNode.next;
			}
		}
	}
	boolean contains(T key) {
		boolean res = false;
		if (count != 0) {
			Node<T> iteratorNode = headNode.next;
			while(iteratorNode!=null) {
				if (iteratorNode.element.equals(key)) {
					res = true;
					break;
				}
				iteratorNode = iteratorNode.next;
			}
		}
		return res;
	}
	boolean remove(T key) {
		boolean res = false;
		if (count != 0) {
			Node<T> preNode = headNode;
			Node<T> curNode = headNode.next;
			for (;curNode != null;curNode = curNode.next) {
				if (curNode.element.equals(key)) {
					preNode.next = curNode.next;
					res = true;
					break;
				}
				preNode = preNode.next;
			}
		}
		return res;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkedList<String> ll = new LinkedList<>();
		ll.insertAtHead("abc");
		ll.insertAtTail("zxy");
		ll.insertAtHead("qwe");
		ll.insertAtTail("gfg");	
		ll.insertAtHead("232");
		ll.insertAtTail("!@#");	
		LinkedList.display(ll);
		System.out.println(ll.contains("!@#"));
		System.out.println(ll.remove("!@#"));
		System.out.println(ll.contains("!@#"));
		}
}
class Node<T> {
	T element;
	Node<T> next;

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值