1.单链表翻转(新指针,两个交换位置,循环调用)
ListNode* ReverseList(ListNode* pHead) {
ListNode* newhead = NULL;
for(ListNode* p = pHead; p; )
{
ListNode* tmp = p -> next;
p -> next = newhead;
newhead = p;
p = tmp;
}
return newhead;
}
2.链表中环的检测(快慢指针相遇)
NODE_t *pSlow = pList;
NODE_t *pFast = pList;
while (pFast != NULL && pFast->pNext != NULL) {
pSlow = pSlow->pNext;
pFast = pFast->pNext->pNext;
if (pSlow == pFast) {
break;
}
}
return (pFast == NULL || pFast->pNext == NULL) ? NULL : pSlow;
3.两个有序链表合并(新指针,两个交换位置,循环调用)
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1 == NULL)
return pHead2;
else if(pHead2 == NULL)
return pHead1;
ListNode* pMergedHead = NULL;
if(pHead1->m_nValue < pHead2->m_nValue)
{
pMergedHead = pHead1;
pMergedHead->m_pNext = Merge(pHead1->m_pNext, pHead2);
}
else
{
pMergedHead = pHead2;
pMergedHead->m_pNext = Merge(pHead1, pHead2->m_pNext);
}
return pMergedHead;
}
4.删除链表中倒数第n个节点(双指针)
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* first=head;
while(n--!=0)
first=first->next;
if(!first)
return head->next;
ListNode* sec=head;
while(first->next!=NULL){
sec=sec->next;
first=first->next;
}
sec->next=sec->next->next;
return head;
}
5.链表的中间节点(快慢指针)
SListNode * FindMidNode(SListNode * phead)
{
SListNode *fast = phead;
SListNode *slow = phead;
while (fast)
{
if (fast->next != NULL)
{
fast = fast->next->next;
}
else
{
break;
}
slow = slow->next;
}
return slow;
}