摘要: Given a linked list, return the node where the cycle begins. If there is no cycle, return null.Follow up: Can you solve it without using extra space?思考:第一步:设环长为len,快慢指针q、p相遇时,q比p多走了k*len。 第二部:p先走k*len步,p,q一起走每次一步,相遇时p比q多走了一个环距离,此时q就是环开始结点。通过分析AC的感觉真好!class Solution {public: ListNode *detectCycle(... 阅读全文
posted @ 2013-11-16 12:07 七年之后 阅读(271) 评论(0) 推荐(0) 编辑
摘要: Given a linked list, determine if it has a cycle in it.Follow up: Can you solve it without using extra space?思考:快慢指针,快指针一次走两步,慢指针一次一步。若快指针跟慢指针指向同一个结点,则有环。若快指针到达链表末尾即指向NULL,说明没有环。/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : ... 阅读全文
posted @ 2013-11-16 11:20 七年之后 阅读(208) 评论(0) 推荐(0) 编辑
摘要: Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…You must do this in-place without altering the nodes' values.For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.思考:[微软原题点击]。O(n2)方法这里就不贴了。因为每次要插入的结点都是尾结点,从头结点开始寻找时间都花费在查询上。题意说只可以改变.next,这算是一个提示吧。我们可以翻转待插入链表结点 阅读全文
posted @ 2013-11-16 10:49 七年之后 阅读(293) 评论(0) 推荐(0) 编辑