《Cracking the Coding Interview》——第2章:链表——题目6
2014-03-18 02:41
题目:给定一个带有环的单链表,找出环的入口节点。
解法1:用hash来检测重复节点肯定是容易想而且效率也高的好办法。
代码:
// 2.6 You have a circular Linked List: a->b->c->d->e->c. Find where the cycle starts.
#include <cstdio>
#include <unordered_set>
using namespace std; struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {};
}; class Solution {
public:
ListNode* firstFirstNodeInCycle(ListNode *head) {
if (head == nullptr) {
return head;
} // hash the pointers.
unordered_set<ListNode *> us;
ListNode *ptr; ptr = head;
while (ptr != nullptr) {
if (us.find(ptr) != us.end()) {
// the first node of the cycle is found.
return ptr;
} else {
us.insert(ptr);
ptr = ptr->next;
}
} // the list has no cycle.
return nullptr;
}
}; int main()
{
int i;
int n, k;
int val;
struct ListNode *head, *tail, *ptr;
Solution sol; while (scanf("%d", &n) == && n > ) {
// create a linked list
ptr = head = tail = nullptr;
for (i = ; i < n; ++i) {
scanf("%d", &val);
if (head == nullptr) {
head = ptr = new ListNode(val);
} else {
ptr->next = new ListNode(val);
ptr = ptr->next;
}
}
tail = ptr; // create a cycle in the list
scanf("%d", &k);
if (k >= && k <= n) {
ptr = head;
for (i = ; i < k; ++i) {
ptr = ptr->next;
}
tail->next = ptr;
} // find the first node in the cycle.
ListNode *first_node = sol.firstFirstNodeInCycle(head);
if (first_node != nullptr) {
printf("%d\n", first_node->val);
} else {
printf("no cycle\n");
} /*
// print the list
ptr = head;
for (i = 0; i < n; ++i) {
printf("%d->", ptr->val);
ptr = ptr->next;
}
printf("\n");
*/ // delete the list
for (i = ; i < n; ++i) {
ptr = head->next;
delete head;
head = ptr;
}
} return ;
}
解法2:如果你非不让我用hash,就只有观察一下几个特殊节点了。既然这个环有“第一个”点,那肯定也有“最后一个”点。我特地打了引号,是因为最后一个点恰好指向第一个。如果你从链表的头开始向后遍历,必然是先到达“第一个”,然后才能到达“最后一个的”。只有对于“最后一个”点,才会出现先到达ptr->next,后到达ptr的情况,所以如果存在符合这个情况的节点ptr,ptr->next就是我们要找的环的入口。这种方法效率不高而且不容易想,除了面试之外基本没有别的用处了。但为了面试淘汰一些人,这点用处也很重要了。
代码:
// 2.6 You have a circular Linked List: a->b->c->d->e->c. Find where the cycle starts.
#include <cstdio>
#include <unordered_set>
using namespace std; struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {};
}; class Solution {
public:
ListNode* firstFirstNodeInCycle(ListNode *head) {
if (head == nullptr) {
return head;
} ListNode *p1, *p2; p1 = head;
while (p1 != nullptr) {
p2 = head;
while (p2 != p1->next && p2 != nullptr) {
if (p2 == p1) {
break;
} else {
p2 = p2->next;
}
}
if (p2 == p1->next) {
return p2;
} else {
p1 = p1->next;
}
} return nullptr;
}
}; int main()
{
int i;
int n, k;
int val;
struct ListNode *head, *tail, *ptr;
Solution sol; while (scanf("%d", &n) == && n > ) {
// create a linked list
ptr = head = tail = nullptr;
for (i = ; i < n; ++i) {
scanf("%d", &val);
if (head == nullptr) {
head = ptr = new ListNode(val);
} else {
ptr->next = new ListNode(val);
ptr = ptr->next;
}
}
tail = ptr; // create a cycle in the list
scanf("%d", &k);
if (k >= && k <= n) {
ptr = head;
for (i = ; i < k; ++i) {
ptr = ptr->next;
}
tail->next = ptr;
} // find the first node in the cycle.
ListNode *first_node = sol.firstFirstNodeInCycle(head);
if (first_node != nullptr) {
printf("%d\n", first_node->val);
} else {
printf("no cycle\n");
} /*
// print the list
ptr = head;
for (i = 0; i < n; ++i) {
printf("%d->", ptr->val);
ptr = ptr->next;
}
printf("\n");
*/ // delete the list
for (i = ; i < n; ++i) {
ptr = head->next;
delete head;
head = ptr;
}
} return ;
}
《Cracking the Coding Interview》——第2章:链表——题目6的更多相关文章
- Cracking the Coding Interview:: 寻找有环链表的环路起始节点
给定一个有环链表,实现一个算法返回环路的开头节点. 这个问题是由经典面试题-检测链表是否存在环路演变而来.这个问题也是编程之美的判断两个链表是否相交的扩展问题. 首先回顾一下编程之美的问题. 由于如果 ...
- Cracking The Coding Interview 2.0 单链表
#include <iostream> #include <string> using namespace std; class linklist { private: cla ...
- Cracking the coding interview 第一章问题及解答
Cracking the coding interview 第一章问题及解答 不管是不是要挪地方,面试题具有很好的联系代码总用,参加新工作的半年里,做的大多是探索性的工作,反而代码写得少了,不高兴,最 ...
- 《Cracking the Coding Interview》读书笔记
<Cracking the Coding Interview>是适合硅谷技术面试的一本面试指南,因为题目分类清晰,风格比较靠谱,所以广受推崇. 以下是我的读书笔记,基本都是每章的课后习题解 ...
- Cracking the coding interview
写在开头 最近忙于论文的开题等工作,还有阿里的实习笔试,被虐的还行,说还行是因为自己的水平或者说是自己准备的还没有达到他们所需要人才的水平,所以就想找一本面试的书<Cracking the co ...
- Cracking the Coding Interview(Trees and Graphs)
Cracking the Coding Interview(Trees and Graphs) 树和图的训练平时相对很少,还是要加强训练一些树和图的基础算法.自己对树节点的设计应该不是很合理,多多少少 ...
- Cracking the Coding Interview(Stacks and Queues)
Cracking the Coding Interview(Stacks and Queues) 1.Describe how you could use a single array to impl ...
- Cracking the coding interview目录及资料收集
前言 <Cracking the coding interview>是一本被许多人极力推荐的程序员面试书籍, 详情可见:http://www.careercup.com/book. 第六版 ...
- 《Cracking the Coding Interview》——第2章:链表——题目7
2014-03-18 02:57 题目:检查链表是否是回文的,即是否中心对称. 解法:我的做法是将链表从中间对半拆成两条,然后把后半条反转,再与前半条对比.对比完了再将后半条反转了拼回去.这样不涉及额 ...
随机推荐
- 在windows bat脚本(batch)中延时
编写bat脚本时,有事我们希望在指令和指令之间,加入延时.例如当一条指令执行后,windows需要一定时间来响应的情况. 以下是一种实现方法,通过ping 指令来实现,5表示ping5次,就是延时5秒 ...
- IOS 计算文字尺寸(UILabel)
方式1 :普通用法 #define MJNameFont [UIFont systemFontOfSize:14] /** * 计算文字尺寸 * * @param text 需要计算尺寸的文字 * ...
- POJ-2229 Sumsets---完全背包变形
题目链接: https://vjudge.net/problem/POJ-2229 题目大意: 给定一个N,只允许使用2的幂次数,问有多少种不同的方案组成N. 思路: 处理出2的幂次方的所有的数字,当 ...
- vue中css动画原理
显示原理: <transition name='fade'> <div v-if='show'>hello world</div> </transition& ...
- 离线安装vscode vsix插件
VS代码扩展市场 通过扩展增强Visual Studio代码的强大功能 https://marketplace.visualstudio.com/vscode Visual Studio Code包含 ...
- 线程 task训练
1. task类表示一个线程,最简单的task的构造方法是 ,参数是Action<t>,是一个无返回值的泛型委托. 指向要执行的函数.当调用·start()方法时,就执行子线程.执行指向的 ...
- VMWare关闭beep声
在虚拟机文件夹下找到 .vmx 文件,在文件末尾添加 mks.noBeep = "TRUE" ,重启虚拟机即可.
- phpMyAdmin提示找不到mcrypt和mbstring模块
yum install php-mcryptyum install php-mbstringphp -m 查看是否安装成功 service httpd restart 重启服务器 注: 这里可能会出现 ...
- System.TimeDate
本篇将介绍时间类型. msdn官网:点击查看 时间辅助类:点击查看 方法:计算两个时间的时间差(年月日小时分钟),获取时间戳,时间格式转换,获取时间随机码 定义:表示时间上的一刻,通常以日期和当天的 ...
- Filter,一种aop编程思想的体现
一.filter简介 filter是Servlet规范里的一个高级特性,只用于对request.response的进行修改. filter提出了FilterChain的概念,客户端请求request在 ...