LeetCode:Remove Nth Node From End of List

来源:互联网 发布:网络电影数据分析 编辑:程序博客网 时间:2024/06/05 06:11

题目链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

题目介绍:删除链表倒数第n个结点

解题思路:先遍历一边链表得出该链表的长度,然后计算倒数第n个结点前的结点个数,然后删除链表倒数第n个结点。

代码如下:

class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        int len = 0;        ListNode* node = head;        while (node != NULL) {            node = node->next;            len++;        }        int f = len-n-1;        if (f < 0) {             head = head->next;         } else {            ListNode* a = head;            while (f > 0) {                a = a->next;                f--;            }            a->next = a->next->next;        }        return head;    }};


原创粉丝点击