[leetcode] 19. Remove Nth Node From End of Lis
来源:互联网 发布:sql语句编写技巧 编辑:程序博客网 时间:2024/06/04 18:24
题目:
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个节点,限定n一定是有效的,即n不会大于链表中的元素总数。还有题目要求我们一次遍历解决问题,那么就得想些比较巧妙的方法了。比如我们首先要考虑的时,如何找到倒数第N个节点,由于只允许一次遍历,所以我们不能用一次完整的遍历来统计链表中元素的个数,而是遍历到对应位置就应该移除了。那么我们需要用两个指针来帮助我们解题,pre和cur指针。首先cur指针先向前走N步,如果此时cur指向空,说明N为链表的长度,则需要移除的为首元素,那么此时我们返回head->next即可,如果cur存在,我们再继续往下走,此时pre指针也跟着走,直到cur为最后一个元素时停止,此时pre指向要移除元素的前一个元素,我们再修改指针跳过需要移除的元素即可。
public ListNode removeNthFromEnd(ListNode head,int n){ if(head.next==null) return null; ListNode pre,cur; pre=cur=head; for(int i=0;i<n;i++) cur=cur.next; if(cur==null) return head.next; else{ while(cur.next!=null){ cur=cur.next; pre=pre.next; } } pre.next=pre.next.next; return head; }
阅读全文
0 0
- [leetcode] 19. Remove Nth Node From End of Lis
- LeetCode-19:Remove Nth Node From End of Lis
- [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
- 机器学习算法总结--提升方法
- libevent 示例代码
- jsp页面获取服务器时间
- sublime text 3 安装、添加命令行启动、汉化、注册码
- 游戏开发常用的算法
- [leetcode] 19. Remove Nth Node From End of Lis
- MAVEN的常用操作
- 饿了么项目(二)
- laravel缓存
- 最小生成树之prim算法
- swift中字符串截取
- 向值栈放List集合
- SSM三大框架整合Springfox(Swagger2)步骤以及遇到的一些问题
- ANR