证明单链表有环路:
本文所用的算法 可以 形象的比喻就是在操场当中跑步,速度快的会把速度慢的扣圈
可以证明,p2追赶上p1的时候,p1一定还没有走完一遍环路,p2也不会跨越p1多圈才追上
我们可以从p2和p1的位置差距来证明,p2一定会赶上p1但是不会跳过p1的
因为p2每次走2步,而p1走一步,所以他们之间的差距是一步一步的缩小,4,3,2,1,0
到0的时候就重合...
分类:
其他好文 时间:
2014-09-01 10:48:33
阅读次数:
151
#include
#include
#include
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNod...
分类:
其他好文 时间:
2014-08-31 23:04:12
阅读次数:
287
LeetCode: Reverse Linked ListReverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1->2->3->4->5->NULL, m = 2 ...
分类:
其他好文 时间:
2014-08-31 22:45:51
阅读次数:
215
题意:给定一个单链表,判断该链表中是否存在环,如果存在,返回环开始的节点
思路:
1.定义两个指针,快指针fast每次走两步,慢指针s每次走一次,如果它们在非尾结点处相遇,则说明存在环
2.若存在环,设环的周长为r,相遇时,慢指针走了 slow步,快指针走了 2s步,快指针在环内已经走了 n环,
则有等式 2s = s + nr => s = nr
3.在相遇的时候,另设一个每次走一步的慢指针slow2从链表开头往前走。因为 s = nr,所以两个慢指针会在环的开始点相遇
复杂度:时间O(n)
struct...
分类:
其他好文 时间:
2014-08-30 23:07:40
阅读次数:
187
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is...
分类:
其他好文 时间:
2014-08-30 11:14:19
阅读次数:
209
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the...
分类:
其他好文 时间:
2014-08-30 08:49:59
阅读次数:
210
Given a linked list, swap every two adjacent nodes and return its head.For example,Given1->2->3->4, you should return the list as2->1->4->3.Your algor...
分类:
其他好文 时间:
2014-08-30 01:11:08
阅读次数:
286
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 ...
分类:
其他好文 时间:
2014-08-30 00:06:58
阅读次数:
359
Sort a linked list using insertion sort.
【题意】
用插入排序对一个链表进行排序。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
...
分类:
其他好文 时间:
2014-08-29 21:26:48
阅读次数:
233
# Definition for singly-linked list.class ListNode: def __init__(self, x): self.val = x self.next = Noneclass Solution: # @return ...
分类:
其他好文 时间:
2014-08-29 19:40:58
阅读次数:
164