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. 安装国际版firefox(火狐浏览器)并设置语言为中文

    访问https://www.mozilla.org/zh-CN/firefox/new/?scene=2下载.安装: 访问https://addons.mozilla.org/zh-CN/firefo ...

  2. 获取url中的某个字段的值

    function getUrl(name, url) { url = url || window.location.search; var reg = new RegExp("(^|& ...

  3. 从Java官网下载JDK1.6等低版本JDK

    今天在浏览Java官网的时候发现旧版本(1.8之前)的JDK安装包下载地址没有在下载页面明显的提供出来.个人通过在官网查看,发现oracle官方将旧版本的JDK全都放在Java Archive模块中了 ...

  4. tarjan+topsort

    题目 缩完点后统计入读为零的点就可以来. 因为缩完点后肯定是DAG #include<iostream> #include<cstdio> #include<algori ...

  5. c/c++基础

    如果有你认为重要的知识点,而我这却没有记录下来的,那么期待你分享给我(^U^)ノ~YO. 1.在结构体中,符号->的前面是指针变量,符号.的前面是普通变量.   程序中a->b等价于(*a ...

  6. JS中的var、let、const

    1.var 在全局window中申明则为全局变量,是全局对象 window 的属性. var sum = 0 console.log(window.sum) console.log(sum); 在函数 ...

  7. Subversion简介

    作为一名编程人员,SVN经常作为代码.项目的版本控制,殊不知SVN也可作为其他领域的版本控制,例如对文档.音频.视频等 . SVN可以看成一种文件系统,为了使工作人员提高工作效率,可以进行并行的工作, ...

  8. Unicode编码字符 转换成汉字

    转载:http://www.chengxuyuans.com/iPhone_IOS/48128.html - (NSString *)replaceUnicode:(NSString *)unicod ...

  9. js实现二分查找

    二分查找需要数组是有序的,1.先从有序数组的最中间元素开始查找,如果和要查找的元素相等,直接返回索引,若不相等则下一步.2.如果指定的元素大于或者小于中间元素,则在大于或小于的那一半区域内查找,重复第 ...

  10. Struts2之基于配置的字段校验

    上一篇struts2之输入校验介绍了手动完成输入校验,也即依靠重写validate方法和validateXxx方法,指定请求某个方法时对传入的参数进行校验. 本篇介绍基于配置的字段校验.下面是登录的常 ...