赞
踩
输入:head = [3,2,0,-4],pos = 1
输出:true
输入:head = [1], pos = -1
输出:false
bool hasCycle(struct ListNode *head) {
if(head==NULL){
return false;//如果该链表为空链表,则该链表一定不为环形
}
struct ListNode*end;
end = head;
struct ListNode*new;
new=head;//定义两个指针
while(new!=NULL&&new->next!=NULL){
end=end->next;//第一个指针每次走1步
new=new->next->next;//第二个指针每次走两步
if(new==end){
return true;//如果快指针与慢指针相遇,则证明为环形
break;
}
}
return false;//若快指针与慢指针不相遇则证明不为环形
}
输入:head = [1,2], pos = 0
输出:返回索引为 0
解释:链表中有一个环,其尾部连接到第一个节点。
输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。
struct ListNode*end;
end=head;
struct ListNode*new;
new=head;//定义两个指针
while(new!=NULL&&new->next!=NULL){
end=end->next;//慢指针每次向后移动一位
new=new->next->next;//快指针每次向后移动两位
if(end==new){
break;
}
}
if(new==NULL||new->next==NULL){
return NULL;//若不为环形链表,则返回NULL
}
struct ListNode*new1;//定义新的指针
new1=head;
while(new1!=new){
new=new->next;
new1=new1->next;
}
return new1;//当新的指针与旧的指针相遇,返回
}
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA==NULL||headB==NULL){
return NULL;
//如果链表为空}
struct ListNode*new1;
new1 = headA;
struct ListNode*new2;
new2 = headB;
while(new1!=new2){
new1=(new1==NULL)?headB:new1->next;
//如果new1为空,new1为headB否则new1取下一个new2=(new2==NULL)?headA:new2->next;
//如果new2为空, new2为headA否则new2取下一个}
return new1;
}
n
个结点,并且返回链表的头结点。输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode*new1;
struct ListNode*new2;
new1=head;
new2=head;
for(int i=1;i<=n;i++){
new1=new1->next;
//让快指针先运动n步}
if(new1==NULL){
return head->next;//如果new1为空,删除的头结点
}
while(new1->next!=NULL){
new1=new1->next;
new2=new2->next;
}
//当快指针为空时,慢指针的下一步就为要删除的节点new2->next=new2->next->next;
return head;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。