LeetCode 19. Remove Nth Node From End of List 解题报告
来源:互联网 发布:java项目log4j冲突 编辑:程序博客网 时间:2024/04/28 07:45
题目描述:
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.
解题思路:
本题即为链表的删除操作。为了使得针对头结点的操作更加简便,所以首先在head前建立一个新的头结点。由于是删除从尾结点开始的第n个结点,所以首先要知道链表中结点的数目,之后计算出要删除的结点即为从首节点开始的第L-n+1(L为链表的长度)个结点。(实现如代码一所示)
由于题目要求Try to do this in one pass,所以代码一显得繁琐一些,可以直接令一个指针tmp指向自己设置的头节点,然后首先向后移动n+1个位置,当tmp指针指向NULL时,pre变为要删除结点的前一个结点,之后进行删除操作即可。(实现如代码二所示)
代码展示:
class Solution {public: //代码一 ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode dummy = ListNode(0); dummy.next = head; int i=-1 ; ListNode* tmp = &dummy; for(;tmp!=NULL;i++) tmp = (*tmp).next; int j = i-n; tmp = &dummy; while(j--) { tmp = (*tmp).next; } ListNode * ans = (*tmp).next; (*tmp).next=(*ans).next; return dummy.next; }};
class Solution {public: //代码二 ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode dummy = ListNode(0); dummy.next = head; //int i=-1 ; ListNode* tmp = &dummy; ListNode* pre = &dummy; for(int i=0;i<=n;i++) tmp = (*tmp).next; while(tmp!=NULL) { tmp= (*tmp).next; pre= pre->next; } (*pre).next = (*(*pre).next).next; return dummy.next; }};
0 0
- LeetCode解题报告--Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List 解题报告
- [LeetCode] 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. 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@Java解题报告
- Remove Nth Node From End of List 解题报告
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- LeetCode --- 19. Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- 二进制中1的个数
- linux free command
- HTML概述
- 游戏类别整理
- Q配置管理和文档管理
- LeetCode 19. Remove Nth Node From End of List 解题报告
- Ionic 热更新
- C++ 泛型基础
- 安卓智慧上海学习笔记系列——请求父控件不要拦截当前控件事件
- Java 生成数字证书系列(一)了解数字证书
- 完美世界运营培训生内推笔试题
- PAT(乙级)1004 福尔摩斯的约会 (20)
- 9接口-Java编程思想
- Java Unreachable code