7. 微软亚院之编程判断俩个链表是否相交

来源:互联网 发布:剑灵怎样导入捏脸数据 编辑:程序博客网 时间:2024/04/29 17:34
给出俩个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交。
为了简化问题,我们假设俩个链表均不带环。
问题扩展:
1.如果链表可能有环列?

2.如果需要求出俩个链表相交的第一个节点列?


HANDWRITING:

simple question:

bool simpleIntersect(node *h1, node *h2) {if (h1 == 0 || h2 == 0) return false;while (h1->next != 0) h1 = h1->next;while (h2->next != 0) h2 = h2->next;return h1 == h2;}
question 1:

bool loop (node *a, node * &s) {node *slow = a, *fast = a;while (fast->next != 0 && fast != 0) {slow = slow->next;fast = fast->next->next;if (fast == slow) {fast = a;while (slow != fast) {slow = slow->next;fast = fast->next->next;}s = fast;return true;}}return false;}bool intersect(node *h1, node *h2) {node *sh1, *sh2;bool lh1 = loop(h1, sh1), lh2 = loop(h2, sh2);if (lh1 != lh2) return false;if (!lh1 && !lh2) return simpleIntersect(h1, h2);return sh1 == sh2;}

1、记错找环起点的方法

具体看:http://blog.csdn.net/lalor/article/details/7628332

慢指针走过的路程s1 = 非环部分长度 + 弧长

快指针走过的路程s2 = 非环部分长度 + n*环长 + 弧长

s1 *2 = s2, 可得非环部分长度 = n*环长 - 弧长

while (fast != slow) {          fast = fast->next;          slow = slow->next;  } 


question 2:

node *intersect(node *a, node *b) {if (a == 0 || b == 0) return 0;int al = 0, bl = 0, dl = 0;while (a->next != 0) { a = a->next; ++al;}while (b->next != 0) {b = b->next;++bl;}if (al > bl) {dl = al - bl;while (dl--) a = a->next;} else {while (dl--) b = b->next;}while (a->next != 0 &&b->next != 0) {if (a == b) return a;a = a->next;b = b->next;}return 0;}

ANSWER FROM:http://blog.csdn.net/v_july_v/article/details/6870251

struct Node {  int data;  int Node *next;};// if there is no cycle.int isJoinedSimple(Node * h1, Node * h2) {  while (h1->next != NULL) {    h1 = h1->next;  }  while (h2->next != NULL) {    h2 = h2-> next;  }  return h1 == h2;}// if there could exist cycleint isJoined(Node *h1, Node * h2) {  Node* cylic1 = testCylic(h1);  Node* cylic2 = testCylic(h2);  if (cylic1+cylic2==0) return isJoinedSimple(h1, h2);  if (cylic1==0 && cylic2!=0 || cylic1!=0 &&cylic2==0) return 0;  Node *p = cylic1;  while (1) {    if (p==cylic2 || p->next == cylic2) return 1;    p=p->next->next;    cylic1 = cylic1->next;    if (p==cylic1) return 0;  }}Node* testCylic(Node * h1) {  Node * p1 = h1, *p2 = h1;  while (p2!=NULL && p2->next!=NULL) {    p1 = p1->next;    p2 = p2->next->next;    if (p1 == p2) {      return p1;    }  }  return NULL;}

原创粉丝点击