Cracking the Coding Interview Q2.1

本博客记录我用C++刷cracking the coding interview的历程。。。

可能有很多思路不是最简的,但是绝对原创(好吧,有时想不出来也会翻翻书后答案,看看java代码。。)

原则上是一天一道题,有时简单的20分钟就能搞定。。。复杂的,或者是进入下一章节,需要重新写class,会比较耗时间。。。也许得2、3个小时。。可能会第一天写一个类,第二天再做题。。希望在圣诞节放假的时候能刷接近100道吧。圣诞节+寒假一定要怒刷!!争取明年能找到理想工作。。话说考算法的都是牛公司。。。。。。。

说了那么多废话。。开始说Q2.1

题干如下:

/* Write code to remove duplicates from an unsorted linked list.
 * FOLLOW UP
 * How would you solve this problem if a temporary is not allowed? */
我用了2种方法,一种是用了temporary space的,另外一种是没用的,直接用指针。。

/* delDup() used the temporary buffer */
void linkedlist::delDup() {
	print();
	if (isEmpty());
	else {
		node* current = head;
		node* prev = head;
		bool letter[128] = {false};
		while (current != NULL) {
			int val = current->character;
			if(letter[val]) {
				prev->next = current->next;
				current = current->next;
			}
			else {
				letter[val] = true;
				prev = current;
				current = current->next;
			}
		}
	}
	print();
}

首先是用了temporary space的。。。基本思路就是由于ASCII码为0-127.。。。我就设定一个数组letter[128],如果相应字符首次出现,则将相应letter[ascII]设为true,所以,当下次检测到为true的时候,则知道重复,此时删除该node。。

然后是第二种纯用指针的方法。。

/* delDup2() did not use temporary buffer */
void linkedlist::delDup2() {
	print();
	node* current = head;
	node* prev = head;
	if (isEmpty())
		;
	else if (current->next == NULL)
		;
	else {
		while (current != NULL) {
			node* temp = current->next;
			prev = current;
			while (temp != NULL) {
				if(temp->character == current->character) {
					prev->next = temp->next;
					temp = temp->next;
				}
				else {
					prev = temp;
					temp = temp->next;
				}
			}
			current = current->next;
		}
	}
	print();
}
前两个判断就是如果该linked list为空或者只有1个node,都不做任何处理。。

之后才是比较重要的,

构建一个双重循环,current为外层,然后从current node开始的下一个元素进行内层循环,如果找到与current node相等的元素,则将其删除。。。然后继续搜索。。

最后,补上完整源码,https://github.com/YimengL/CTCI-cpp/blob/master/2_1.cpp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值