數據結構複習(5)---單鏈表

上一章:數據結構複習(4)—隊列

package cjy.datastructure;

/**
 * 節點 Title: Node.java 單鏈表
 * 
 * @author CJY》10258
 * @date 2019年7月12日
 */
public class Node {
	/**
	 * 節點對應的值(數值域)
	 */
	int data;
	/**
	 * 下一個節點的位置(節點域)
	 */
	Node next = null;

	/**
	 * 構建新節點
	 * 
	 * @param data
	 *            節點的值
	 */
	public Node(int data) {
		this.data = data;
	}

	/**
	 * 鏈接下一個節點
	 * 
	 * @param node
	 * @return
	 */
	public Node append(Node newNode) {
		// 當前節點位置
		Node curNode = this;
		// 遍歷整個鏈表
		while (true) {
			Node nextNode = curNode.next;
			// 如果發現某個節點的next爲空,則說明可以在該節點上鍊接新節點,跳出循環
			if (nextNode == null) {
				break;
			}
			// 將上面找到的節點作爲當前節點(其實就是鏈表最後一個節點的位置)
			curNode = nextNode;

		}
		// 將新節點賦值給當前節點(在鏈表結尾加入新節點)
		curNode.next = newNode;
		return this;
	}

	/**
	 * 轉到下一個節點位置
	 * 
	 * @return
	 */
	public Node next() {
		return this.next;
	}

	/**
	 * 獲取當前節點的值
	 * 
	 * @return
	 */
	public int getData() {
		return this.data;
	}

	/**
	 * 判斷當前節點是否是最後一個節點
	 * 
	 * @return
	 */
	public boolean isLastNode() {
		return this.next == null;
	}

	/**
	 * 在當前節點後面插入新節點
	 * 
	 * @param newNode
	 */
	public void insertNode(Node newNode) {
		// 爲空則直接插入,表尾
		if (this.next == null) {
			this.next = newNode;
		} else {
			Node node = next;
			this.next = newNode;
			newNode.next = node;
		}
	}

	/**
	 * 刪除當前節點的下一個節點
	 */
	public void removeNode() {
		if (this.next == null) {
			throw new RuntimeException("無下一個節點");
		}
		Node node = next.next;
		this.next = node;
	}

	/**
	 * 獲取節點長度
	 * 
	 * @return
	 */
	public int length() {
		Node curNode = this;
		int count = 0;
		while (true) {
			count++;
			curNode = curNode.next;
			if (curNode == null) {
				break;
			}
		}
		return count;
	}

	/**
	 * 打印所有節點
	 */
	public void showNode() {
		Node curNode = this;
		while (true) {
			System.out.print(curNode.data + " ");
			curNode = curNode.next;
			if (curNode == null) {
				break;
			}
		}
		System.out.println();
	}
}

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