c_cpp 从列表末尾删除第N个节点http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 从列表末尾删除第N个节点http://oj.leetcode.com/problems/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 * first = new ListNode(0);
        first->next = head;
        ListNode * fast = first;
        ListNode * slow = first;
        int i = n;
        while(i > 0){
            fast = fast->next;
            i--;
        }
        if(fast == NULL){
            return NULL;
        }
        while(fast->next != NULL){
            fast = fast->next;
            slow = slow->next;
        }
        ListNode * temp = slow->next;
        slow->next = temp->next;
        delete temp;
        
        head = first->next;
        delete first;
        return head;*/
        ListNode * fast = head;
        ListNode * slow = head;
        int i = n;
        while(i > 0){
            fast = fast->next;
            i--;
        }
        if(fast == NULL ){ // remove head 
            ListNode * temp = head;
            head = head->next;
            delete temp;
            return head;
        }
        while(fast->next != NULL){
            fast = fast->next;
            slow = slow->next;
        }
        ListNode * temp = slow->next;
        slow->next = temp->next;
        delete temp;
        
        return head;
    }
};

以上是关于c_cpp 从列表末尾删除第N个节点http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 从列表末尾删除第N个节点http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

c_cpp 从链接列表的末尾开始编程第n个节点

java 19.从列表末尾删除第N个节点(#)。java

java 19.从列表末尾删除第N个节点(#)。java

java 19.从列表末尾删除第N个节点(#)。java

java 19.从列表末尾删除第N个节点(#)。java