力扣160. 相交链表
1、C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { if(headA==NULL||headB==NULL)return NULL; struct ListNode* p = headA; struct ListNode* q = headB; while(p!=q){ if(p!=NULL){ p = p->next; } else{ p = headB; } if(q!=NULL){ q = q->next; } else{ q = headA; } } return q; }
2、C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(!headA||!headB)return NULL; ListNode *p = headA; ListNode *q = headB; while(p!=q){ if (p) p = p->next; else p = headB; if(q) q = q->next; else q = headA; } return p; } };
3、JAVA
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null||headB==null)return null; ListNode p = headA; ListNode q = headB; while(p!=q){ if(p!=null) p = p.next; else p = headB; if(q!=null) q = q.next; else q = headA; } return p; } }
4、Python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if headA is None or headB is None:return None p = headA q = headB while p!=q: if p is None: p = headB else: p = p.next if q is None: q = headA else: q = q.next return p标签:ListNode,struct,next,链表,算法,headB,headA,return,四种 From: https://www.cnblogs.com/cmkbk/p/17298000.html