删除链表的第N个节点

删除链表的第N个节点,第1张

1,删除链表节点时,删除头节点和其他节点的 *** 作不一样,为了统一删除节点的 *** 作,增加虚拟头节点将大大简化 *** 作。



2,双指针对于处理数组和链表的问题较为方便和快捷。


#include 

using namespace std;

struct link_list{
    int data;
    link_list * next;
    link_list(int val = 0,link_list * ptr = nullptr):data(val),next(ptr){}
};

class Solution{
public:
    link_list * deleteReindexNode(link_list * head,int index){
        link_list * pre_head = new link_list (INT16_MAX);
        pre_head->next = head;
        link_list * slow = pre_head;
        link_list * fast = slow;

        while(index--){
            fast = fast->next;
        }
        
        while(fast->next){
            slow = slow->next;
            fast = fast->next;
        }
        
        slow->next = slow->next->next;
        
        return pre_head->next;
    }

};

int main()
{
    link_list * head = new link_list (1);
    head = new link_list (2,head);
    head = new link_list (3,head);
    head = new link_list (4,head);

    Solution solution;
    link_list * cur_list = solution.deleteReindexNode(head,1);

    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/568939.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存