LeetCode-19. 删除链表的倒数第N个节点(Remove Nth Node From End of List)

双指针

/**
 * 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 ans(0);
    	ans.next = head;
        ListNode *after = &ans, *now = &ans;
        for(int i = 0; i < n; i++) {
        	after = after->next;
        }
        while(after->next){
        	now = now->next;
        	after = after->next;
        }
        now->next = now->next->next;
        return ans.next;
    }
};

题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/submissions/

发布了42 篇原创文章 · 获赞 2 · 访问量 1418

猜你喜欢

转载自blog.csdn.net/Listen_heart/article/details/103056940