19. Remove Nth Node From End of

2019-05-19  本文已影响0人  jecyhw

题目链接

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;
    }
};
上一篇下一篇

猜你喜欢

热点阅读