Personal implementation of JAVA's linked list (JAVA's reference is actually an implicit pointer)

package com.alist;


class alist<K>
{
	private Object val;
	private alist<K> head,now,temp,next;
	private int length = 0;
	
	public alist()
	{
		head = now = this;
	}
	
	public Object get(int Count)
	{
		temp = head;
		for(int i=0;i<length;i++)
		{
			if(i==Count)
			{
				return temp.val;
			}
			temp = temp.next;
		}
		return null;
	}
	
	public int getLength()
	{
		return this.length;
	}
	
	public void add(K InVal)
	{
		now.val = InVal;
		now.next = new alist<K>();
		now = now.next;
		this.length ++;
	}
}


public class test1
{
	public static void main(String[] args)
	{
		/*The creation of object-oriented linked list objects is similar to List *head=(List*)malloc(sizeof(List)); in C language, in fact, new is to allocate suitable memory space to the object*/
		alist<Integer> list = new alist<Integer>();
		/* Example of using object-oriented linked list */
		for(int i=0;i<20;i++) list.add(i);
		for(int i=0;i<list.getLength();i++) System.out.println(list.get(i));
		/*How to implement an example similar to C language passing in a pointer to modify the pointer corresponding to the address saved by the pointer, basic types such as int, basically cannot do this kind of thing, in short, only the things that come out of new have It may be done (not all of them), because all addresses are passed when passed, and int is passed by value directly in java*/
	}

}



     In fact, it can be found intuitively that I have packaged the operations of the linked list in alist, which can avoid the bugs caused by the irregular operation of the linked list by others. For example, when this class is submitted to other programmers, they only need to know how to use add and The get method is enough, and the remove and the like are too lazy to write, anyway, JAVA itself has ArrayList to realize the linked list function, I just write a small example


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519150&siteId=291194637