题目描述
判断给定的链表中是否有环。如果有环则返回true,否则返回false。
你能给出空间复杂度的解法么?
说明:本题目包含复杂数据结构ListNode,点此查看相关信
#define Node ListNode
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL || head->next==NULL) return false;
Node*first = head,*last = first;
while(first && first->next ){
first=first->next->next,last=last->next;
if(first==last) break;
}
if(first && first->next && first==last) return true;
return false;
}
};
题目描述
给定一个链表,删除链表的倒数第n个节点并返回链表的头指针
例如,
给出的链表为:1->2->3->4->5, n= 2.
删除了链表的倒数第n个节点之后,链表变为1->2->3->5.
备注:
题目保证n一定是有效的
请给出请给出时间复杂度为 O(n) O(n)的算法
#define Node ListNode
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(n<=0 ||head==NULL) return head;
Node dummy(0);
dummy.next = head;
head = &dummy;
Node*first=head,*last=head;
for(int i=0;i<n;++i) first = first->next;
while(first->next) first=first->next,last=last->next;
//找到了
Node* x = last->next;
last->next = x->next;
delete x;
return dummy.next;
}
};
找到链表环的入口
#define Node ListNode
#define null NULL
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
//2N 的路程
if(head==null || head->next ==null) return null;
Node* first=head,*last = head;
while(first&& first->next) {
first = first->next->next;
last = last ->next;
if(first==last) {
while(head!=first) head=head->next,first=first->next;
return head;
}
}
return null;
}
};