java实现链表

链表分为arraylist和linklist

主要实现链表的建立,链表的输出,链表的查找,链表的插入,链表的删除功能

建立链表有头插法和尾插法

package wd;
class LinkNode{
	public LinkNode next;
	public int data;
	public LinkNode(int data) {
		this.data=data;

	}
}
class sx{
	public LinkNode head;
	public LinkNode tail;
	int size=0;
	public sx() {
		head=null;
		tail=null;
	}
	//头插法
	public void createhead(int data) {
		LinkNode newNode=new LinkNode(data);
		if(head==null) {
			head=newNode;
			tail=newNode;
		}
		else {
			newNode.next=head;
			head=newNode;

			
		}
		size++;
		print(head);
		
	}
	//尾插法
	public void createtail(int data) {
		LinkNode newNode=new LinkNode(data);

		if(head==null) {
			head=newNode;
			tail=newNode;
		}
		else {
			tail.next=newNode;
			newNode.next=null;
			tail=newNode;
			
			
		}
		size++;	
		print(head);
			
		}
	public void delete(int index) {
		LinkNode old=head;
		LinkNode pre=head.next;
		while(head!=null) {
			if(head.data==index) {
				pre.next=head.next;
				head.next=null;
			}
			pre=head;
			head=head.next;
		}
		print(old);

		
		
	}
	public void insert(int index,int data) {
		LinkNode old=head;
		LinkNode newdata=new LinkNode(data);
		while(head!=null) {
			if(head.data==index) {
				newdata.next=head.next;
				head.next=newdata;
			}
			head=head.next;
		}
		print(old);

		

		
		
		
	}
	public LinkNode query(int index) {
		while(head!=null) {
			if(head.data==index) {
				return head;
			}
			head=head.next;
		}
		return null;
		
	}
	public void print(LinkNode head) {
		while(head!=null) {
			System.out.println(head.data);
			head=head.next;
		}
		
	}
	
}

public class linklist {
	public static void main(String[] args) {
		sx test=new sx();
		test.createhead(1);	
		test.createhead(2);	
		test.createhead(3);	
		test.createhead(4);
		//System.out.println("删除值为2的元素后");
		//test.delete(2);
		///System.out.println("插入值为2的元素后");
		//test.insert(1,2);
		LinkNode yuansu=test.query(2);
		System.out.println(yuansu.data);






		
	}
	
}

 

你可能感兴趣的:(算法)