1.链表是否成环的算法
用2个游标进行遍历,一个步长为2,先出发;一个步长为1,后出发,如果后出发的游标能追上前面的游标,则存在环。
2.一次遍历得到链表倒数第N个节点
用2个游标进行遍历,一个步长为2,先出发;一个步长为1,后出发,如果后出发的游标能追上前面的游标,则存在环。
2.一次遍历得到链表倒数第N个节点
- struct iNode {
- int value;
- iNode * next;
- };
- iNode * getresult(iNode * head,int n)
- {
- iNode *pfirst;
- iNode *psecond;
- pfirst=head;
- int counter;
- for(counter=0;counter<n;counter++) {
- pfirst=pfirst->next;
- }
- psecond=head;
- while(pfirst!=NULL) {
- pfirst=pfirst->next;
- psecond=psecond->next;
- }
- return psecond;
- }