(四)5个常见的链表操作

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;  
}  

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值