LeetCode 19. Remove Nth Node From End of List
来源:互联网 发布:淘宝投诉处理流程 编辑:程序博客网 时间:2024/05/29 19:46
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.
Subscribe to see which companies asked this question.
把一个单向链表的倒数第n个节点去掉。
这个题很简单的思路就是:先遍历一遍链表得到长度,找到第len-n+1个元素跳过即可:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { int len = 0; ListNode q = head; while(q!=null){ q = q.next; len++; } if(len==1||len==n){ return head.next; } ListNode p = head; for(int i=0;i<len;i++){ if(i+n+1==len){ p.next = p.next.next; break; } else p = p.next; } return head; }}而更简单的方法则是不需要获取长度,而是先找到正数第n个元素,并让一个指针指向它,另一个指针指向head,两个指针同时前进,直到第一个指针为null,此时跳过第二个指针的元素即可。
0 0
- 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
- [Leetcode] 19. Remove Nth Node From End of List
- [leetcode] 19.Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 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)
- 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从基础开始_05IO流的体系
- 关于UnicodeDecodeError: 'gbk' codec can't decode byte的解决办法
- 数据库分组查询
- POJ NOI0105-39 与7无关的数(Bailian2701)
- NSMutableArray与NSMutableIndexSet结合删除NSMutableArray中符合条件的object
- LeetCode 19. Remove Nth Node From End of List
- python爬取彩票网站开奖号码
- 文件上传与下载
- 字符串练习题
- 初窥Linux 之 文件权限
- 关于ThinkPHP下使用Uploadify插件提示HTTP Error (302)错误的解决办法
- C# static详解
- POJ 1837 Balance
- 11、Anaconda 快速入门