數據結構之單向鏈表

概述:實現一個帶頭節點的單向鏈表
單向鏈表:
    所謂單向鏈表,指的是隻能從頭部往尾部遍歷的鏈表。
    單向鏈表的每個節點有兩個區域,一個用來存儲數據,另一個用來指向下一個節點。

實現:
1、節點類

public class Node {
    int data;
    Node next;
    public Node() {}
    public Node(int data) {
        this.data=data;
    }
}


2、功能實現

public class LinkList {

	private Node head;
	private Node tail;
	private int size;

	public LinkList() {
		head = new Node();
		tail = head;
		size = 0;
	}

	/**
	 * 在尾部添加一個元素
	 */
	public boolean add(int data) {
		boolean result = false;
		Node temp = new Node(data);
		tail.next = temp;
		tail = temp;
		size++;
		result = true;
		return result;
	}

	/**
	 * 從尾部移除一個元素
	 */
	public boolean remove() {
		boolean result = false;
		Node node = head;
		int index = size - 1;
		while (index > 0) {
			node = node.next;
			index--;
		}
		tail = node;
		node.next = null;
		size--;
		result = true;
		return result;
	}

	/**
	 * 刪除指定位置的元素
	 */
	public boolean delete(int index) {
		isCrossing(index);
		boolean result = false;
		Node node = head;
		int indexTemp = index;
		while (index > 0) {
			node = node.next;
			index--;
		}
		if (indexTemp == size - 1) {
			tail = node;
			node.next = null;
		} else {

			node.next = node.next.next;
		}
		size--;
		result = true;
		return result;
	}

	/**
	 * 在指定位置插入一個元素
	 */
	public boolean insert(int index, int data) {
		isCrossing(index - 1);
		boolean result = false;
		Node temp = new Node(data);
		int indexTemp = index;
		Node node = head;
		while (index > 0) {
			node = node.next;
			index--;
		}
		if (indexTemp == size) {
			node.next = temp;
			tail = node.next;
		} else {
			temp.next = node.next;
			node.next = temp;
		}

		size++;
		result = true;
		return result;
	}

	/**
	 * 更改指定位置的元素
	 */
	public boolean modify(int index, int data) {
		isCrossing(index);
		boolean result = false;
		Node node = head;
		while (index > 0) {
			node = node.next;
			index--;
		}
		node = node.next;
		node.data = data;
		result = true;
		return result;
	}

	/**
	 * 獲取指定位置的元素
	 */
	public int get(int index) {
		isCrossing(index);
		int result = 0;
		Node node = head.next;
		while (index > 0) {
			node = node.next;
			index--;
		}
		result = node.data;
		return result;
	}

	/**
	 * 獲取鏈表長度
	 */
	public int getSize() {
		return size;
	}

	/**
	 * 校驗下標是否越界
	 * 
	 * @param index
	 */
	private void isCrossing(int index) {
		if (!(index < size)) {
			Exception exception = new IndexOutOfBoundsException();
			try {
				throw exception;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章