LeetCode 算法习题 第四周
来源:互联网 发布:美容院微管理软件 编辑:程序博客网 时间:2024/06/05 18:59
19. Remove Nth Node From End of List
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个节点
我的解答:
/** * 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) { ListNode* fast = head; ListNode* slow = head; if(n==0)return head;//此时不删除节点,直接返回head for(int i = 0; i < n; i++) fast = fast -> next;//将fast和slow拉开长为n的距离 if(fast == NULL) return head->next;//如果时删除第一个节点,就直接返回head->next,否则在下面的循环 head -> next 就会报错了 while(fast->next != NULL){ fast = fast->next; slow = slow->next; }//将fast移动到最后,同时移动slow if(slow != NULL) slow -> next = slow ->next ->next;//删去中间节点,可以不判断slow,因为先前已经讨论过n=0的情况了 return head; }};
阅读全文
0 0
- LeetCode 算法习题 第四周
- LeetCode 算法习题 第四周
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- 第四周LeetCode算法题两道
- LeetCode 算法习题 第一周
- 第四周 习题
- leetcode-python 第四周
- leetcode-第四周
- 第四周leetcode题
- [leetcode] 第四周作业
- LeetCode题解 第四周
- 第四周LeetCode
- 算法课程Leetcode作业第四周技术博客
- ODBC
- HTML中的标签系列-03-DIV标签&CSS
- HTTP与HTTPS的区别
- 第三周第一课
- 【计蒜客】X的平方根
- LeetCode 算法习题 第四周
- 转载:数据库相关中间件
- 搭建Hadoop集群
- CREST: Convolutional Residual Learning for Visual Tracking
- 深入理解Java中的final关键字
- acm 输入输出处理入门 A+B(I) C++实现
- bzoj1014 [JSOI2008]火星人prefix ( splay + hash )
- Python 修改目录下所有文件名为MD5
- hdu1559 最大子矩阵