1、160相交链表
不是两链表值相等,而是指向同一个空间
先将较长的链表头指针后移至两链相同长度的位置
/**
* 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) {
int len1=0;
int len2=0,n,i;
ListNode* p=headA;
ListNode* q=headB;
ListNode* h=headB;
while(p!=NULL)
{
len1++;
p=p->next;
}
while(q!=NULL)
{
len2++;
q=q->next;
}
if(len1>len2)
{
n=len1-len2;
for(i=0;i<n;i++)
{
headA=headA->next;
}
}
else if(len1<len2)
{
n=len2-len1;
for(i=0;i<n;i++)
{
headB=headB->next;
}
}
while(headA)
{
headB=h;
while(headB){
if(headA==headB)
{
return headA;
}
headB=headB->next;
}
headA=headA->next;A
}
return NULL;
}
};
2、环形链表
set集合
set<ListNode*> list;
list.insert() 插入
list.count(a) 判断list中是否有a
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
set<ListNode*> list;
while(head)
{
if(list.count(head))
{
return true;
}
list.insert(head);
head=head->next;
}
return false;
}
};