Java 版本的单项链表插入

本文分享了一次面试经历,作者被要求手写单项链表的插入操作。文章提供了两种实现方式:一种是非递归的循环插入,另一种是递归插入。通过实际代码对比两种方法,总结了面试经验和教训。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:今天去一家公司去面试,聊了一会然后让我手写一段单项链表的插入,其实题目很简单。可是自己把自己绕到递归中去了。然后我就呵呵了。

晚上下班回家,自己又重新整理了一下思路,写了一下代码。将两种方式都实现一下,一种是面试官的想法,一种是我的递归,呵呵,总之都实现了。

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;
	}
}

当面试的时候,自己思路一下子没有想到点子上,就会越想越钻牛角尖,然后变得紧张,导致思路越来越模糊。

说明自己还是没有沉住气,心态还需要磨练。

技术还不过硬啊,明显还需要提高。

最后想说一句话:我叫不紧张,呵呵。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值