LeetCode 算法学习(7)

题目描述

Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.

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.

题目大意

删除倒数第N个结点。

思路分析

设置p,q两个指针,p指向开始结点,q指向第n个结点,两个指针同时向后移动,当q指向尾部时,p就为倒数第n个结点,删除p即可。

关键代码

    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *p = head, *q = head;
        for (int i = 0; i < n; i++) {
            q = q->next;
        }
        if (q == NULL) {
            head = head->next;
            delete p;
            return head;
        }
        while (q->next != NULL) {
            p = p->next;
            q = q->next;
        }
        if (p->next != NULL){
            ListNode *temp = p;
            p = p->next;
            temp->next = p->next;
        } else {
            delete p;
            return NULL;
        }
        delete p;
        return head;
    }

总结

这道题目有应用到一定的逆向思维,总体不难;要注意删除第一个结点时的特殊情况。

猜你喜欢

转载自blog.csdn.net/L_Realoo/article/details/85270054
今日推荐