1. 程式人生 > >手動實現LinkedList, 增加新增節點方法 (4)

手動實現LinkedList, 增加新增節點方法 (4)

package com.jianshun;

public class Node {

	Node previous; //上一個節點
	Node next;  //下一個節點
	Object element;  //元素資料
	public Node(Node previous, Node next, Object element) {
		super();
		this.previous = previous;
		this.next = next;
		this.element = element;
	}
	public Node(Object element) {
		super();
		this.element = element;
	}
}
package com.jianshun;
/**
 * 自定義一個連結串列
 * 插入節點
 * @author Administrator
 *
 */
public class SxtLinkedList04 {

	private Node first;
	private Node last;
	
	private int size;
	
	public void add(int index,Object obj){
		Node newNode = new Node(obj);
		Node temp = getNode(index);

		if(temp!=null){
			Node up = temp.previous;
			if(up == null){//把元素插入到位首
				first = newNode;
				newNode.next = temp;
				temp.previous = newNode;
			}else if(size == index){//將元素插入到末尾
				//待續
			}else{
				up.next = newNode;
				newNode.previous = up;
				newNode.next = temp;
				temp.previous = newNode;
			}
		}
		size++;
	}
	
	//[]
	//['a','b','c']
	public void add(Object obj){
		Node node = new Node(obj);
		
		if(first == null){
			
			node.previous = null;
			node.next = null;
			
			first = node;
			last = node;
		}else{
			node.previous = last;
			node.next = null;
			
			last.next = node; 
			last = node;
		}
		size++;
	}			
	
	//根據下標刪除資料
	public void remove(int index){
		Node temp = getNode(index);
		 
		if(temp != null){
			Node up = temp.previous;
			Node down = temp.next;
			
			//被刪除的元素是第一個時
			if(index == 0){
				first = down;
			}
			
			//被刪除的元素是最後一個時候
			if(index == size-1){
				last = up;
			}
			
			if(up!=null){
				up.next = down;
			}
			if(down!=null){
				down.previous = up;
			}
			size--;
		}
	}
	
	//根據下標獲取節點(程式碼重用)
	public Node getNode(int index){
		Node temp = null;
		if(index <= (size>>1)){ //size >>1 相當於除以2
			temp = first;
			for(int i=0; i<index; i++){
				temp = temp.next;
			}
		}else{
			temp = last;
			for(int i=size-1; i>index; i--){
				temp = temp.previous;
			}
		}
		return temp;
	}
	
	
	//[]
	//[a,b,c,d,e,f]  c-2
	public Object get(int index){
		
		if(index <0 || index >size - 1){
			throw new RuntimeException("索引數字不合法:"+index);
		}		
		Node temp = getNode(index);
		return temp !=null ? temp.element : null;
	}		
	
		
	@Override
	public String toString() {
		//[a,b,c] first=a, last=c
		StringBuilder sb = new StringBuilder("[");
		Node temp = first;
		while(temp != null){
			sb.append(temp.element+",");
			temp = temp.next;
		}
		sb.setCharAt(sb.length()-1, ']');
		return sb.toString();
	}
	
	
	
	public static void main(String[] args) {
		SxtLinkedList04 list = new SxtLinkedList04();
		
		list.add("a");
		list.add("b");
		list.add("c");
		list.add("d");
		list.add("e");
		list.add("f");
		
		//list.remove(5);
		//list.add(3,"老高");
		//list.add(0,"老陳");
		list.add(5,"凡凡");
		System.out.println(list);
	}	
		
		
}