C++ 优化笔录(1)

快指针和慢指针

ListNode *slow=head;
ListNode *fast=head;
while(fast)
{
	slow=slow->next;
	fast = fast->next ? fast->next->next: fast->next;
}

快指针指向末尾,退出循环

链表翻转(递归)

ListNode* rev(ListNode* h)
{
    if(h==NULL or h->next==NULL)
        return h;
    ListNode *p=rev(h->next);
    h->next->next=h;
    h->next=NULL;
    return p;
}

还有一种借助临时变量

链表翻转(借助临时变量)

 ListNode* reverseList(ListNode* head)
{
	 ListNode *p1,*p2;
	 p1 = head;
	 p2 = NULL;
	 if(p1 == NULL) return head;
	 while(p1 != NULL)
	 {
		ListNode *temp = p1->next;
		p1->next = p2;
		p2 = p1;
		p1 = temp;
	 }
	 return p2;
}

你可能感兴趣的:(C++)