1、 Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* 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) {
if(head == NULL || head -> next == NULL)
return false;
ListNode *fast = head;
ListNode *slow = head;
while(fast -> next && fast -> next -> next){
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow)
return true;
}
return false;
}
};
判断链表是否有环的经典做法就是快慢指针,定义两个指针,慢指针一次走一步,快指针一次走两步,如果有环,一定相遇,如果遇到空指针就没有环啦。
注意判定条件:fast->next为空时,fast->next->next是不存在的,会出现内存访问错误,所以要先判断fast->next。由于上一步判定了fast->next->next不为空,则下一步的fast一定不为空指针,就不用担心fast->next不存在的问题。slow就更不用管了,fast都判过了嗯~
- break 结束循环,跳出循环体;
continue 结束本次循环,进行下次循环;
return 跳出循环体所在的方法,相当于跳出循环体。
2、 Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head||!head->next)
return true;
ListNode* fast=head;
ListNode* slow=head;
while(fast->next&&fast->next->next){
slow=slow->next;
fast=fast->next->next;
}
slow->next=reverse(slow->next);
slow=slow->next;
while(slow){
if(head->val!=slow->val)
return false;
head=head->next;
slow=slow->next;
}
return true;
}
ListNode* reverse(ListNode* head){
ListNode dummy(-1);
ListNode* pre=&dummy;
pre->next=head;
ListNode* cur=head;
while(cur&&cur->next){
ListNode* temp=pre->next;
pre->next=cur->next;
cur->next=cur->next->next;
pre->next->next=temp;
}
return dummy.next;
}
};
这道题也用了快慢指针的方法是因为当慢走一步快走两步时,慢指针刚好可以走到链表的length/2(向下取整)位置,将后面一半用链表反转的方法实现后连起来就可以按顺序比较了。。。