数据结构—单链表

public class singleLinkedList<T> {

	/**
	 * 结点类
	 */
	private static class Node<T>
	{
		T nodeValue;//数据域
		Node<T> nextNode;//指针域
		Node(T nodeValue,Node<T> nextNode){
			this.nodeValue=nodeValue;
			this.nextNode=nextNode;
		}

        Node(T nodeValue){
			this(nodeValue, null);
		}
	}
	//下面是singleLinkedList 类的数据成员和方法
	private Node<T> head,tail;
	public singleLinkedList() {
	head=tail=null;
	}
	public boolean isEmpty() {
		return head==null;
	}
	
	//添加头结点
	public void addToHead(T iteam) {
		head=new Node<T>(iteam);
		if(tail==null)tail=head;
	}
	//添加尾指针
	public void addToTail(T item) {
		if(!isEmpty()){
			tail.nextNode=new Node<T>(item);
			tail=tail.nextNode;
		}
		else {
			head=tail=new Node<T>(item);
		}
	}
    private void printList() {
		if(isEmpty()){
			System.out.println("null");
		}
		else {
			for(Node<T> pNode=head;pNode!=null;pNode=pNode.nextNode){
				System.out.println(pNode.nodeValue);
			}
		}
	}
	//表头插入结点
    private void addFirst(T item) {
		Node<T> newNode=new Node<T>(item);
		newNode.nextNode=head;
		head=newNode;
	}
    //表尾插入结点
    private void addLast(T item) {
		Node<T> newNode=new Node<T>(item);
		tail.nextNode=newNode;
		tail=newNode;
	}
   
    //表头删除结点
    private void removeFirst () {
		if(!isEmpty()){
			head=head.nextNode;
		}
		else {
			System.out.println("the list is null now");
		}
	}
    //表尾删除结点,效率低,全部遍历
    public void removeLast() {
		Node<T> prevNode=null,currNode=head;
		while(currNode.nextNode!=null){
			prevNode=currNode;
			currNode=currNode.nextNode;
			if(currNode.nextNode==null)prevNode.nextNode=null;
		}
	}
    //遍历方便,可以hasnext函数
    private boolean insert(T appointedItem,T item) {
		Node<T> prevNode=head,currNode=head.nextNode,newNode;
		newNode=new Node<T>(item);
		if(!isEmpty()){
			while ((currNode!=null)&&(!appointedItem.equals(currNode.nodeValue))) {
				prevNode=currNode;
				currNode=currNode.nextNode;
			}
			newNode.nextNode=currNode;
			prevNode.nextNode=newNode;
			return true;
		}
		return false;
	}
    //删除中间结点
    private void remove(T item) {
		Node<T> currNode=head,prevNode=null;
		boolean found=false;
		while(currNode!=null&&!found){
			if(item.equals(currNode.nodeValue)){
				if(prevNode==null)removeFirst();
				else prevNode.nextNode=currNode.nextNode;
				found=true;
			}
			else {
				prevNode=currNode;
				currNode=currNode.nextNode;
			}
		}
	}
    public static void main(String[] args) {
		singleLinkedList<Integer> ls=new singleLinkedList<Integer>();
         ls.addToHead(1);
         ls.addLast(2);
         ls.addLast(4);
         ls.insert(4, 3);
         ls.printList();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值