[关闭]
@snuffles 2019-04-10T17:50:58.000000Z 字数 311 阅读 839

L160 相交链表

链表


编写一个程序,找到两个单链表相交的起始节点。

解:分别遍历两个链表,得到分别对应的长度,然后求长度的差值,把比较长的那个链表向后移动这个差值的个数,然后一一比较。

  1. ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
  2. if (!headA) return NULL;
  3. if (!headB) return NULL;
  4. ListNode * p = headA;
  5. ListNode * q = headB;
  6. for(;p!=NULL;p=p->next){
  7. for(q=headB;q!=NULL;q=q->next){
  8. if (p == q) return p;
  9. }
  10. }
  11. return NULL;
  12. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注