[LeetCode]Remove Nth Node From End of List

栏目: 编程工具 · 发布时间: 8年前

内容简介:Given a linked list, remove theGivenCould you do this in one pass?

原题

Given a linked list, remove the n -th node from the end of list and return its head.

Example:

Given linked list: <strong>1->2->3->4->5</strong>, and <strong><em>n</em> = 2</strong>.

After removing the second node from the end, the linked list becomes <strong>1->2->3->5</strong>.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

思路

首先,明确题意。题目给出了一个只有后继(successor),没有前驱(predecessor)的一个单向链表。要求删除倒数第n个节点。

那么,思路自然会想到的就是在一次遍历就搞定题目要求。所以,我们自然要在遍历的过程中保存一些状态值。那么,这个状态值无非就是目标节点(要删除节点,即第n个节点)的 前驱 。这样,才能将目标节点干掉。

那么,在遍历时,达到目标节点前驱的条件(时刻)是什么?即

cur_l - n > 0

`cur_l`指的是当前遍历的节点个数(即长度),n即题目指定的入参。细细品味,即可明白。

代码

/**
 * 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) {
        auto cur_node = head, search_node = head;
        int cur_l = 1;
        while (cur_node->next != NULL) {
            cur_node = cur_node->next;
            if (++cur_l - n > 1) search_node = search_node->next;
        }
        if (cur_l - n > 0) {
            search_node->next = (search_node->next == NULL) ? NULL : search_node->next->next;
        } else {
            head = head->next;
        }
        return head;
    }
};

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

文章来源: 胡小旭 => [LeetCode]Remove Nth Node From End of List


以上所述就是小编给大家介绍的《[LeetCode]Remove Nth Node From End of List》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

解放战争(上)(1945年8月—1948年9月)

解放战争(上)(1945年8月—1948年9月)

王树增 / 人民文学出版社 / 2009-8 / 60.00

《解放战争》为王树增非虚构文学著述中规模最大的作品。武器简陋、兵力不足的军队对抗拥有现代武器装备的兵力庞大的军队,数量不多、面积有限的解放区最终扩展成为九百六十万平方公里的共和国,解放战争在短短四年时间里演绎的是人类历史上的战争传奇。国际风云,政治智慧,时事洞察,军事谋略,军队意志,作战才能,作品具有宏阔的视角和入微的体察,包含着惊心动魄的人生沉浮和变幻莫测的战场胜负,尽展中国历史上规模最大的一场......一起来看看 《解放战争(上)(1945年8月—1948年9月)》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换