1. 程式人生 > >java 泛型練習——用泛型實現單鏈表

java 泛型練習——用泛型實現單鏈表

用泛型實現單鏈表

package com.example;
/**
* 類說明  用泛型實現單鏈表
* 描述:TODO
* @author 佳萌
* @date 2018年5月31日
* 
*/
class Entry<T>{
		public T data;
		public Entry next;
		public Entry() {
			this.data = null;
			this.next = null;
		}
		public Entry(T data) {
			this.data = data;
			this.next = null;
		}
	}
class Link<T>{
	Entry head;
	public Link() {
		head = new Entry();
	}
	/**
	 * 頭插法
	 */
	public void insertHead(T val){
		Entry entry = new Entry(val);
		entry.next = head.next;
		head.next = entry;
	}
	/**
	 * 尾插法
	 */
	public void insertTail(T val){
		Entry entry = new Entry(val);
		Entry p = head;
		while(p.next != null){
			p = p.next;
		}
		p.next = entry;
	}
	public int getLength(){
		Entry p = head;
		int len = 0;
		while(p.next != null) {
			len++;
			p = p.next;
		}
		return len;
	}
	/**
	 * 指定位置插入
	 */
	public boolean insert(T val,int pos){
		Entry p = head;
		Entry entry = new Entry(val);
		int len = 0;
		if(pos < 0 ||pos > this.getLength()){
			return false;
		}
		while(p != null){
			if(len == pos){
				entry.next = p.next;
				p.next = entry;
				return true;
			}
			len++;
			p = p.next;
		}
		return false;
	}
	/**
	 * 
	 * @param val
	 * @return
	 * 刪除指定資料
	 */
	public boolean delete(T val){
		Entry p = head;
		while(p.next != null){
			if(p.next.data == val){
				p.next = p.next.next;
				return true;
			}
			p = p.next;
		}
		return false;
	}
	public void print(){
		Entry p = head.next;
		while(p != null){
			System.out.print(p.data+"   ");
			p = p.next;
		}
	}
}
public class TestDemo3 {
	public static void main(String[] args) {
		Link<Double> l2 = new Link<Double>();
		l2.insertHead(10.0);
		l2.insertHead(20.0);
		l2.insertHead(30.0);
		l2.insertTail(11.0);
		l2.insertTail(22.0);
		l2.insertTail(33.0);
		l2.insert(12.0, 3);
		l2.insert(23.0, 3);
		l2.insert(34.0, 3);
		System.out.println();
		System.out.println(l2.getLength());
		l2.delete(22.0);
		l2.print();	
	}
}