LeetCode 19_Remove Nth Node From End of List
来源:互联网 发布:mysql btree索引原理 编辑:程序博客网 时间:2024/05/18 04:00
这是第二次写这道题了,因为刚才整理博客的时候出了差错,把这一题搞丢了,所以只能重新写一遍了,好在这一题比较简单,没有太多内容,顺便说一句今天正好是农历八月十五,中秋节,祝大家中秋节快乐哈
先看一下这道题吧
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.
Note:
Given n will always be valid.
Try to do this in one pass.
题目的要求很直接,就是让删除链表中倒数第n个数,这个应该是前面这些题中最简单的一道了吧,只要你对链表这种数据结构有一点儿了解,那这题就是小儿科了,出题人貌似也明白这一点,所以要求大家do this in one pass。大家是不是不知道什么叫one pass啊,没关系,我用32级英语水平告诉大家,do this in one pass,就是让你一次性通过,不要再跟个做针线活儿的大妈似的对你的程序缝缝补补的。
链表是一种很重要的数据结构,其特性也是很多的,我们这里不能把数据结构这门课都给大家讲一遍,只能把这道题用到的链表特性稍微给大家普及一下,不啰嗦了,看代码吧
//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) {if(head==NULL)return head;ListNode* cur=head;int lst_len=0;while(cur!=NULL){cur=cur->next;lst_len++;}if(lst_len==n) return head->next;int f=lst_len-n;cur=head;for(int i=0;i<f-1;++i){cur=cur->next;}cur->next=cur->next->next;return head; }};看了代码,就更加觉得没什么好说的了,这里就考察到了链表的两种特性,当然也是最重要的特性:
首先,也就是链表这种数据结构的最重要缺点,那就是非随机访问的特性。也就是说它不能像数组一样用下标来访问数据,所以要找到某一个元素或者得到其长度就必须从头开始顺藤摸瓜历遍整个链表,这就浪费了很多时间。
其次,是链表作为重要数据结构的最大优点,那就是增删数据不用移动其他元素,只需一句话即可,这一点是数组望尘莫及的。
最后跟大家说一下数据结构的重要性,数据结构是计算机专业的灵魂课程,而数据结构和算法这一对基友天生就生一对,更有大神说过,程序=数据结构+算法。所以大家如果要想学好程序设计,那数据结构这门课是一定要好好研究一下的。
最最后,中秋快乐!
- LeetCode 19_Remove Nth Node From End of List
- leetcode 第一刷_Remove Nth Node From End of List
- 0019_Remove Nth Node From End of List
- 19_Remove Nth Node From End of List徒手尝试#2(Done)
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- LeetCode(19) Remove Nth Node From End of List
- [LeetCode 19] Remove Nth Node From End of List Solutions
- leetcode 19 Remove Nth Node From End of List
- Leetcode【19】:Remove Nth Node From End of List
- [leetcode 19] Remove Nth Node From End of List
- [Leetcode] 19 - Remove Nth Node From End of List
- LeetCode | #19 Remove Nth Node From End of List
- leetcode.19----------Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- LeetCode 19 Remove Nth Node From End of List
- 3.3.3 Differ对象
- HDU 1181 DFS
- PAT(甲级)1035
- 静态成员函数的作用与静态数据成员的初始化
- PAT(甲级)1036
- LeetCode 19_Remove Nth Node From End of List
- 我读过的好书
- phpt文件说明,php官方自动测试方法,run-test.php命令用法
- 工具提示
- PAT(甲级)1037
- HDU - 1024 Max Sum Plus Plus(DP + 滚动数组)
- imread
- String,StringBuffer,StringBuild的区别
- HTML元素是什么?