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的更多相关文章

  1. Cracking the Coding Interview:: 寻找有环链表的环路起始节点

    给定一个有环链表,实现一个算法返回环路的开头节点. 这个问题是由经典面试题-检测链表是否存在环路演变而来.这个问题也是编程之美的判断两个链表是否相交的扩展问题. 首先回顾一下编程之美的问题. 由于如果 ...

  2. Cracking The Coding Interview 2.0 单链表

    #include <iostream> #include <string> using namespace std; class linklist { private: cla ...

  3. Cracking the coding interview 第一章问题及解答

    Cracking the coding interview 第一章问题及解答 不管是不是要挪地方,面试题具有很好的联系代码总用,参加新工作的半年里,做的大多是探索性的工作,反而代码写得少了,不高兴,最 ...

  4. 《Cracking the Coding Interview》读书笔记

    <Cracking the Coding Interview>是适合硅谷技术面试的一本面试指南,因为题目分类清晰,风格比较靠谱,所以广受推崇. 以下是我的读书笔记,基本都是每章的课后习题解 ...

  5. Cracking the coding interview

    写在开头 最近忙于论文的开题等工作,还有阿里的实习笔试,被虐的还行,说还行是因为自己的水平或者说是自己准备的还没有达到他们所需要人才的水平,所以就想找一本面试的书<Cracking the co ...

  6. Cracking the Coding Interview(Trees and Graphs)

    Cracking the Coding Interview(Trees and Graphs) 树和图的训练平时相对很少,还是要加强训练一些树和图的基础算法.自己对树节点的设计应该不是很合理,多多少少 ...

  7. 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 ...

  8. Cracking the coding interview目录及资料收集

    前言 <Cracking the coding interview>是一本被许多人极力推荐的程序员面试书籍, 详情可见:http://www.careercup.com/book. 第六版 ...

  9. 《Cracking the Coding Interview》——第2章:链表——题目7

    2014-03-18 02:57 题目:检查链表是否是回文的,即是否中心对称. 解法:我的做法是将链表从中间对半拆成两条,然后把后半条反转,再与前半条对比.对比完了再将后半条反转了拼回去.这样不涉及额 ...

随机推荐

  1. mysql : 修改数据库权限

    解决步骤 第一步,点击用户 注意!!! 编辑权限,在我们设置权限之前,我们需要先重新加载才能生效, 如果不用编辑的话,直接按重新载入编辑,这个相当于保存. 中文意思(注意看那段话) 第二步 选择要处理 ...

  2. API:Sign签名的执行流程

    Sign签名存在目的:为了防止不法分子修改参数数据,进而攻击服务器,导致数据泄露或从中获得利益    例如:一个接口是用户把积分转帐给他的朋友,修改后,变为转帐到攻击者的帐户,这样,攻击者就能得到利益 ...

  3. ubuntu linux断点续传下载工具 uGet 的安装

    网址 http://ugetdm.com/downloads-ubuntu 使用命令行安装 sudo add-apt-repository ppa:plushuang-tw/uget-stable s ...

  4. 同步软件UltraCompare 64位 软件及注册机

    软件及注册机下载: https://share.weiyun.com/f09e6243887e374ead1b3a3ab8f611a9 软件官方下载地址:  https://www.ultraedit ...

  5. GL格式一览表

  6. 在写EF 时把时间格式化的做法

    SELECT COUNT(l.LogSeq), date_format(l.CreateDate,'%Y-%m') CreateDateByMonth FROM LOL l WHERE l.Creat ...

  7. jsc

    之前发现一个神器,js代码测试脱离浏览器,mac终端也可以做到 调试js的时候,一般都是用浏览器的开发者工具,这里给大家推荐另外一种,抛开浏览器,在终端执行的方式,Mac内置了一个javascript ...

  8. Centos6.4环境下DNS服务器的搭建

    DNS服务器搭建很繁琐吗?给你个简单的招吧! 配置域主服务器 阶段: 1.在bind的主配置文件中添加该域 2.在/var/named中创建该域的zone文件 3.编辑zone文件,添加需要的信息 4 ...

  9. python导入其他文件夹下的.py文件

    想在globalpararm中导入read_config中的类 import sys sys.path.append('..') from common.read_config import Read ...

  10. ibator自动代码生成

    首先,强烈推荐一篇文章,介绍的特详细 http://www.iteye.com/topic/821983 1. 插件安装 http://blog.csdn.net/rchm8519/article/d ...