[LeedCode OJ]#19 Remove Nth Node From End of List

【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】

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

题意:

给出一个链表,要求删除倒数第n个节点

思路:

还是使用双指针法,让第一个指针领先第二个指针n-1的距离,当第一个指针到达了链表尾部的时候,那么第二个指针就是指向的倒数第n个结点了

/** * 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 *first = head;ListNode *second = head;ListNode *pre = nullptr;for(int i = 1; i<n; i++)first = first->next;while(first->next){pre = second;first = first->next;second = second->next;}if(pre==nullptr)head = second->next;elsepre->next = second->next;return head;}};

版权声明:本文为博主原创文章,如果转载,请注明出处

,如果说人生啊,尝过一回痛快淋漓的风景,

[LeedCode OJ]#19 Remove Nth Node From End of List

相关文章:

你感兴趣的文章:

标签云: