Java 版本的單項鍊表插入

前言:今天去一家公司去面試,聊了一會然後讓我手寫一段單項鍊表的插入,其實題目很簡單。可是自己把自己繞到遞歸中去了。然後我就呵呵了。

晚上下班回家,自己又重新整理了一下思路,寫了一下代碼。將兩種方式都實現一下,一種是面試官的想法,一種是我的遞歸,呵呵,總之都實現了。

import java.util.Random;

/**
 * 單項列表插入的測試類
 * @date 2016-09-18 
 * @author Henry
 *
 */
public class YKLinkList {
	public static void main(String[] args) {
		LinkList list = new LinkList();
		Random random = new Random();
		for (int i = 0; i < 10; i++) {
			//面試官提到的簡單的方式。
			//list.insert(random.nextInt(10));
			//我把自己想到的遞歸寫了一下。
			list.insert2(random.nextInt(10));
		}
		//打印輸出一下
		Node head = list.head;
		while (head != null) {
			System.out.println(head.val);
			head = head.next;
		}
	}
}
/**
 * 節點的定義,很簡單是吧,都沒有用泛型
 * @date 2016-09-18 
 * @author Henry
 *
 */
class Node {
	int val;
	Node next;
	public Node(int val, Node next) {
		this.val = val;
		this.next = next;
	}

	public Node(int val) {
		this(val, null);
	}

	public Node() {
	}
}
/**
 * 單項列表的定義
 * @date 2016-09-18 
 * @author Henry
 *
 */
class LinkList {
	
	Node head;//定義頭節點

	/**
	 * 面試官的想法,用while循環來做插入。確實簡單,當時爲什麼產生盲區了呢。我也不得而知啊。
	 * @date 2016-09-18 
	 * @param a 要插入的數值。
	 */
	void insert(int a) {
		if (head == null) {
			head = new Node(a);
			return;
		}
		Node head2 = head;
		while (head2 != null) {
			if(head2.val>a){
				head=new Node(a);
				head.next=head2;
				break;
			}
			if (head2.val <= a && head2.next == null) {
				head2.next = new Node(a);
				break;
			}
			if (head2.val <= a && head2.next.val > a) {
				Node next = head2.next;
				head2.next = new Node(a, next);
				break;
			}
			head2 = head2.next;
		}
	}
	/**
	 * 這是我當時不知道爲什麼就陷入遞歸中了,並且當時手寫代碼的時候,一塌糊塗。
	 * @date 2016-09-18 
	 * @param a
	 */
	void insert2(int a) {
		/*
		 * 遞歸自增
		 */
		head=insert0(a, head);
	}
	/**
	 *  重新定義遞歸方法,這種寫法JDK很多地方都有見到。
	 * @param a
	 * @param head2
	 * @return 返回的永遠都是頭節點。
	 */
	Node insert0(int a,Node head2){
		if (head2 == null) {
			head2 = new Node(a);
			return head2;
		}
		if(head2.val>a){
			Node info=new Node(a);
			info.next=head2;
			return info;
		}
		if (head2.val <= a && head2.next == null) {
			head2.next = new Node(a);
			return head2;
		}
		if (head2.val <= a && head2.next.val > a) {
			Node next = head2.next;
			head2.next = new Node(a, next);
			return head2;
		}
		head2.next=insert0(a,head2.next);
		return head2;
	}
}

當面試的時候,自己思路一下子沒有想到點子上,就會越想越鑽牛角尖,然後變得緊張,導致思路越來越模糊。

說明自己還是沒有沉住氣,心態還需要磨練。

技術還不過硬啊,明顯還需要提高。

最後想說一句話:我叫不緊張,呵呵。

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