leetcode Remove Nth Node from Linked List

来源:互联网 发布:2016剑三毒姐捏脸数据 编辑:程序博客网 时间:2024/06/05 10:40
/** * 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) {        if(head == NULL){            return NULL;        }        ListNode* fast = head, *slow = head;        for(int i = 0; i < n; ++i){            fast = fast->next;        }        //if we want to delete the first node of linked list        if(fast == NULL){            ListNode* tmp = slow->next;            delete slow;            return tmp;        }        while(fast->next != NULL){            slow = slow->next;            fast = fast->next;        }            ListNode* tmp = slow->next->next;            ListNode* tode = slow->next;            slow->next = tmp;            delete tode;        return head;    }};
0 0
原创粉丝点击