其他分享
首页 > 其他分享> > 双指针系列1

双指针系列1

作者:互联网

 

这道题目没什么好说的,就是分为两种情况,要删除的链表节点是头结点和要删除的节点是非头结点

 ListNode* deleteNode(ListNode* head, int val) {

        if(head==NULL) return NULL;

        ListNode *ptr=head;

        if(ptr->val==val) return ptr->next ;

        while(ptr->next!=NULL&&ptr->next->val!=val)

        {

            ptr=ptr->next;

        }

        ptr->next=ptr->next->next;

        return head;

    }

 

这题我们可以维护两个指针,一个快指针和一个慢指针先让快指针先走k步,那么之后再同时走,当快指针到达链表尾部的时候,慢指针刚好能指向我们需要返回的链表

 ListNode* getKthFromEnd(ListNode* head, int k) {

        if(head==NULL) return NULL;

        ListNode *faster=head;

        ListNode *low =head;

       while(faster&&k--)

       {

           faster=faster->next;

       }

       while(faster)

       {

           faster=faster->next;

           low=low->next;

       }

       return low;

    }

标签:head,ListNode,faster,next,系列,ptr,指针
来源: https://blog.csdn.net/weixin_39889618/article/details/123245728