一,链表
定义:
struct link_node {
int value;
struct link_node * next;
};
1. 判断链表是否有没有环
使用两个快慢指针
慢指针往后面以动一个节点
快指针每次移动两个节点
// check whether the link list is a ring
// 1 for true, and 0 for false.
int isRing(struct link_node* head) {
if (head == NULL) return 0;
struct link_node* fast = head->next, * slow = head;
while (fast->next && fast->next->next && slow->next) {
if (fast == slow)
return 1;
fast = fast->next->next;
slow = slow->next;
}
return 0;
}
2. 判断两个链表是否重叠
两个链表A,B 假设其长度分别为n,m。 假设n>m
将链表A的指针先以动n-m为,然后再跟B链表同时开始遍历
int getLength(struct link_node * head) {
int len = 0;
while(head) {
len++;
head = head->next;
}