摘要: 这题目还是慢有意思的。题目:0.如何判断单链表里面是否有环?算法的思想是设定两个指针p, q,其中p每次向前移动一步,q每次向前移动两步。那么如果单链表存在环,则p和q相遇;否则q将首先遇到null。这里主要理解一个问题,就是为什么当单链表存在环时,p和q一定会相遇呢?假定单链表的长度为n,并且该单链表是环状的,那么第i次迭代时,p指向元素i mod n,q指向2i mod n。因此当i≡2i(mod n)时,p与q相遇。而i≡2i(mod n) => (2i - i) mod n = 0 => i mod n = 0 => 当i=n时,p与q相遇。这里一个简单的理解是,p和 阅读全文
posted @ 2011-12-19 15:46 zp_Alex 阅读(2026) 评论(0) 推荐(0) 编辑
摘要: 思想为:head指针不断后移,指针反向即可,代码为:#include <stdio.h>#include <conio.h>#include <malloc.h>#include <stdlib.h>typedef struct node{ int data;struct node *next;}node,*LinkList;void creat(LinkList &L){ node *p,*q;L=(LinkList)malloc(sizeof(node)); if (L==NULL) { exit(0); } L->next=N 阅读全文
posted @ 2011-12-19 13:41 zp_Alex 阅读(2243) 评论(0) 推荐(0) 编辑