Leetcode之删除链表

利用快慢指针来解决此问题 ,具体代码如下.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* fast=head;
        ListNode* cur=new ListNode(0); cur->next=head;
        ListNode* slow=cur;
        for(int i=0;i<n;i++)fast=fast->next;
         while(fast)
         {
             fast=fast->next;
             slow=slow->next;
         }
        slow->next=slow->next->next;
        return cur->next;
    }
};
发布了22 篇原创文章 · 获赞 2 · 访问量 2976

猜你喜欢

转载自blog.csdn.net/qq_40623603/article/details/105578563
今日推荐