美文网首页
19. Remove Nth Node From End of

19. Remove Nth Node From End of

作者: jecyhw | 来源:发表于2019-05-19 21:12 被阅读0次

    题目链接

    https://leetcode.com/problems/remove-nth-node-from-end-of-list/

    解题思路

    先链表反转,再删除,最后再反转。(看题解的思路更简单)

    代码

    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            if (head == NULL) {
                return NULL;
            }
            head = revert(head);
            if (n == 1) {
                head = head -> next;
            } else {
                ListNode *cur = head, *next = head->next;
                for (int i = 2; i < n; ++i) {
                    cur = next;
                    next = cur->next;
                }
                cur->next = next->next;
            }
            return revert(head);
        }
    
        ListNode* revert(ListNode *head) {
            if (head == NULL || head->next == NULL) {
                return head;
            }
    
            ListNode *end = head, *tmp;
            head = head->next;
            end->next = NULL;
    
            while (head != NULL) {
                tmp = head->next;
                head->next = end;
                end = head;
                head = tmp;
            }
            return end;
        }
    };
    

    相关文章

      网友评论

          本文标题:19. Remove Nth Node From End of

          本文链接:https://www.haomeiwen.com/subject/iifczqtx.html