第六周LeetCode
来源:互联网 发布:浙大网新恒天软件福利 编辑:程序博客网 时间:2024/05/22 15:01
题目
难度 Medium
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.
Note:
Given n will always be valid.
Try to do this in one pass.
实现思路
这个题目好像一起上课讨论过,所以大概记得one pass怎么做。大概就是用三个指针(两个也可以),分别是prev,cur,nNext,prev为cur当前节点的前一个节点,而nNext就是当前节点往后数的第n个节点,比如有链表1->2->3->4->5, n = 2,cur为2这个节点,则prev为1节点,nNext为4节点。当nNext为链表最后一个节点的下一个(即为NULL)时,cur就是要找的从end开始第n个节点。即遍历链表时一直把nNext当成end,则cur为要删除的那个,当链表遍历结束即nNext为空,就找到cur了。
如果cur为头指针,删除时要特殊处理。
实现代码
/** * 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* prev = NULL; ListNode* cur = head; ListNode* nNext = head; int count = 0; while (nNext != NULL) { count++; if (count > n) { prev = cur; cur = cur->next; } nNext = nNext->next; } if (prev == NULL) { cur = head; head = head->next; delete cur; } else { prev->next = cur->next; delete cur; } return head; }};
阅读全文
0 0
- leetcode-python 第六周
- 第六周leetcode题
- 第六周LeetCode
- 第六周LeetCode
- [leetcode] 第六周作业
- LeetCode第六周
- 第六周LeetCode
- LeetCode题解 第六周
- leetcode第六周解题报告
- Leetcode 算法习题 第六周
- 第六周LeetCode算法题两道
- Leetcode 算法习题 第六周
- 第六周:[Leetcode]127. Word Ladder
- 第六周:[Leetcode]100. Same Tree
- 第六周:[Leetcode]112. Path Sum
- 第六周:[Leetcode]113. Path Sum II
- 第六周:[Leetcode]437. Path Sum III
- 第六周:[Leetcode]257. Binary Tree Paths
- flume架构图
- JDBC连接和DBUtils的使用详解
- Java算法——判断一个数是否是回文数
- 51nod 1586 约数和
- 【数据结构】顺序存储——定义
- 第六周LeetCode
- 【小项目】Spring boot基于Redis缓存商城分类,商品信息(含源码下载)
- Executing an update/delete query(未开启事务)
- Educational Codeforces Round 30
- 去除数组重复元素的四种方法
- 各个模型特征总结学习
- js笔记—— 基础部分一
- 问题总结(1)
- poj 2367 Genealogical tree (拓扑排序)