目录

手写linklist实现查找插入删除以及获取链表长度

目录

手写linklist实现查找插入删除以及获取链表长度

https://i-blog.csdnimg.cn/direct/f8addcfd4675456d8ad58247649692d5.png

package LinkByHand;

public class LinkList {
	public Node head =null;
	//尾插法
	public void insert(int value) {
		Node node = new Node(value);
		if(head ==null) {
			head =node;
			return;
		}
		Node index = head;
		while(index.next!=null) {
			index =index.next;
		}
		index.next = node;
	}
	
	
	//头插法
	public void insertHead(int value) {
		Node node = new Node(value);
		if(head ==null) {
			head =node;
			return;
		}
		node.next =head;
		head=node;
	}
	
	//获取链表的长度
	public int getLen() {
		int count = 0;
		Node index = head;
		while(index!=null) {
			count++;
			index =index.next;
		}
		return count;
	}
	
	//链表中查数据
	public int search(int value) {
		int position =-1;
		Node index = head;
		while(index!=null) {
			position++;
			if(index.value==value) {
				
				return position;
		}
		index =index.next;
	}
		return -1;
	
	}	

	
	//指定位置插入
	public void insertAtPosition(int value,int position) {
		if(position<0||position>getLen()) {
			System.out.println("插入位置不合理");
			return;
		}
		
		if(position==0) {
			insertHead(value);
		}else  if(position==getLen()){
			insert(value);
		}else {
			Node node =new Node(value);
			Node index =head;
			Node pre = null;
			int current =0;
			while(index!=null) {
				if(current==position) {
					node.next = index;
					pre.next =node;
					return;
				}
				pre = index;
				index =index.next;
				current++;
			}
		}
		
		
		
	}
	
	//删除指定位置的节点
	public void deleteAtPosition(int position) {
		if(position<0||position>=getLen()) {
			System.out.println("删除位置不合理");
			return;
		}
		if(position==0) {
			head =head.next;
		}else {
			Node index = head;
			Node pre =null;
			int current =0;
			while(index!=null) {
				if(current==position) {
					//delete
					pre.next=index.next;
					return;
				}
				pre =index;
				index =index.next;
				current++;
			}
		}
	}
	
	
	
	
	//输出链表中的值	
	@Override
	public String toString() {
		String res="[ ";
		Node index =head;
		while(index!=null) {
			res+=index.value+" ";
			index =index.next;
		}
		res+="]";
		return res;
	}
}