博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Remove Nth Node From End of List --移除链表中的倒数第k个元素
阅读量:4107 次
发布时间:2019-05-25

本文共 840 字,大约阅读时间需要 2 分钟。

问题:

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

For 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.
解答:

注意如果移除的元素是头元素的话,需要特别的处理,否则的话直接找到倒数第n+1个元素,移除它后面的元素即可。

代码:

class Solution {public:    ListNode *removeNthFromEnd(ListNode *head, int n) {        int len=0;        ListNode *pf = head;        while(pf != NULL)        {            ++len;            pf = pf->next;        }        if(len == n)            return head->next;        pf = head;        ListNode *pl = head;        for(int i = 1; i <= n && pf->next != NULL; i++)            pf = pf->next;        while(pf->next != NULL)        {            pf = pf->next;            pl = pl->next;        }        pl->next = pl->next->next;        return head;    }};

转载地址:http://fktsi.baihongyu.com/

你可能感兴趣的文章
postgresql监控工具pgstatspack的安装及使用
查看>>
【JAVA数据结构】双向链表
查看>>
【JAVA数据结构】先进先出队列
查看>>
乘法逆元
查看>>
Objective-C 基础入门(一)
查看>>
Flutter Boost的router管理
查看>>
iOS开发支付集成之微信支付
查看>>
C++模板
查看>>
【C#】如何实现一个迭代器
查看>>
【C#】利用Conditional属性完成编译忽略
查看>>
DirectX11 光照演示示例Demo
查看>>
VUe+webpack构建单页router应用(一)
查看>>
Node.js-模块和包
查看>>
(python版)《剑指Offer》JZ01:二维数组中的查找
查看>>
(python版)《剑指Offer》JZ28:数组中出现次数超过一半的数字
查看>>
(python版)《剑指Offer》JZ30:连续子数组的最大和
查看>>
管理用户状态——Cookie与Session
查看>>
通过Spring Boot三分钟创建Spring Web项目
查看>>
Java编程基础:static的用法
查看>>
Java编程基础:抽象类和接口
查看>>