鍍金池/ 教程/ Java/ Remove Nth Node From End of List(從列表尾部刪除第 N 個結點)
ZigZag Conversion(Z型轉換)
String to Integer (atoi)(轉換到整型)
Generate Parentheses(生成括號)
Longest Common Prefix(最長公共前綴)
Remove Duplicates from Sorted Array(從已排序數(shù)組中移除重復元素)
Swap Nodes in Pairs(交換序列中的結點)
Valid Parentheses(有效的括號)
4 Sum(4 個數(shù)的和)
3 Sum(3 個數(shù)的和)
3 Sum Closest(最接近的 3 個數(shù)的和)
Reverse Nodes in k-Group(在K組鏈表中反轉結點)
Regular Expression Matching (正則表達式匹配)
Two Sum
Container With Most Water(最大水容器)
Merge Two Sorted Lists(合并兩個已排序的數(shù)組)
Remove Nth Node From End of List(從列表尾部刪除第 N 個結點)
String to Integer (atoi)(轉換到整型)
Palindrome Number(回文數(shù))
Longest Substring Without Repeating Characters
Roman to Integer(羅馬數(shù)到整型數(shù))
Integer to Roman(整型數(shù)到羅馬數(shù))
Reverse Integer(翻轉整數(shù))
Merge k Sorted Lists(合并 K 個已排序鏈表)
Implement strStr()(實現(xiàn) strStr() 函數(shù))
Longest Palindromic Substring(最大回文子字符串)
Add Two Numbers
Letter Combinations of a Phone Number(電話號碼的字母組合)

Remove Nth Node From End of List(從列表尾部刪除第 N 個結點)

翻譯

給定一個鏈表,移除從尾部起的第 n 個結點,并且返回它的頭結點。

例如,給定鏈表:1->2->3->4->5,n = 2。

在移除尾部起第二個結點后,鏈表將變成:1->2->3->5。

備注:

給定的 n 是有效的,代碼盡量一次通過。

原文

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

代碼

class Solution{
public:
    ListNode* removeNthFromEnd(ListNode* head, int n){
        ListNode newHead(0);
        newHead.next = head;
        count = n;
        return solution1(&newHead);
    }
private:
    int count;
    ListNode* solution1(ListNode* newHead){
        subSol1(newHead);
        return newHead->next;
    }
    bool subSol1(ListNode* node){
        if(!node) return false;
        if(subSol1(node->next)) return true;
        if(count--) return false;
        ListNode *tmp = node->next;
        node->next = tmp->next;
        delete tmp;
        return true;
    }
};