Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:设定两个指针,一个总比另一个走的快一步,如果有环,那么若干步之后,这两个指针就会相遇
bool hasCycle(ListNode *head)
{
ListNode *p,*q;
if(head==NULL||head->next==NULL)
return false;
*p=head->next;
*q=head->next;
while(p&&p->next)
{
p=p->next->next;
q=q->next;
if(q==p)
{
return true;
}
}
return false;
}
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL )
return head;
ListNode *l = head;
ListNode *q;
while (l&&l->next)
{
q = l->next;
if (q->val== l->val)
{
l->next = l->next->next;
}
else
l = l->next;
}
return head;
}
上题判断是否有环时,判断的是两个数据的地址是否相同,如果相同则存在环,本题中是去除值相同的节点,故要判断指针所指向的值是否相等