删除链表中倒数第n个节点

删除链表中倒数第n个节点

    /**
     * 方法
     * 1.哈希表
     * 2.栈:倒着计算的问题,优先想到,边界条件烦人
     * 3.暴力法:求长度
     * 4.双指针(快慢指针,初始条件,移动策略,边界判断)
     * 5.翻转链表
     * @param head
     * @param n
     * @return
     */
    //栈,时间复杂度,O(n),空间复杂度:O(N)
    ListNode* removeNthFromEnd1(ListNode* head, int n) {
        stack<ListNode*> st;
        //边界条件
        if (head == nullptr)
            return nullptr;
        ListNode* temp = head;
        //计数器,用来倒着计数的
        int count = 1;
        while (temp != nullptr){
            st.push(temp);
            temp = temp->next;
        }
        while (!st.empty()){
            ListNode* temp = st.top();
            st.pop();
            if (count  == n)
            {
                //特殊情况
                if (st.empty()){
                    head = temp->next;
                    break;
                }
                st.top()->next = temp->next == nullptr? nullptr:temp->next;
                delete temp;
                break;
            }
            count++;
        }
        return head;
    }   
 //快慢指针
    ListNode* removeNthFromEnd(ListNode* head, int n){
        //边界条件
        if (head == nullptr)
            return head;
        //快慢指针初始条件
        ListNode* first = head;
        ListNode* second = head;
        //快指针先移动n个位置
        for (int i = 0; i < n; ++i) {
            first = first->next;
        }
        //first为空的时候,表示删除的是头节点
        if (first == nullptr){
            head = head->next;
            return head;
        }
        //当快指针为空时,进行节点删除,或者secon == nullptr
        while (first->next != nullptr){
            first = first->next;
            second = second->next;
        }
        // 删除节点
        ListNode* temp = second->next;
        // 判断second和first是否相邻,相邻的话删除first
        second->next = (temp == first? nullptr:temp->next);
        delete temp;
        return head;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值