【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
来源:互联网 发布:知乎联合创始人 编辑:程序博客网 时间:2024/05/19 16:33
【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
原题
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+1个结点,删除倒数第N个结点就可以了。
代码实现
链表结点类
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; }}
算法实现类
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode pa = head; ListNode pb = head; // 找到第n个结点 for (int i = 0; i < n && pa != null; i++) { pa = pa.next; } if (pa == null) { head = head.next; return head; } // pb与pa相差n-1个结点 // 当pa.next为null,pb在倒数第n+1个位置 while (pa.next != null) { pa = pa.next; pb = pb.next; } pb.next = pb.next.next; return head; }}
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。
特别说明
欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/46997239】
2 0
- 【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
- LeetCode 19 Remove Nth Node From End of List 移除倒数第N个节点
- LeetCode--Remove Nth Node From End of List(移除链表的倒数第N个节点)Python
- leetcode 3. 移除链表的倒数第n个节点 Remove Nth Node From End of List
- leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
- 19. Remove Nth Node From End of List(移除链表的倒数第n个节点)
- [LeetCode-19] Remove Nth Node From End of List(删除倒数第N个节点)
- 19. Remove Nth Node From End of List (移除链表倒数第n个节点)
- LeetCode-19 Remove Nth Node From End of List(移除尾部第N个节点)
- LeetCode | Remove Nth Node From End of List(移除链表中倒数第n个结点)
- Leetcode #19. Remove Nth Node From End of List 移除倒数第N个链表节点 解题小节
- LeetCode(Remove Nth Node From End of List)删除链表倒数第n个节点
- 【LeetCode】Remove Nth Node From End of List 删除链表中倒数第n个节点- Easy +
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- 19.Remove Nth Node From End of List(移除单链表中倒数第N个结点)
- Remove Nth Node From End of List 删除链表倒数第N个节点
- LintCode Remove Nth Node From End of List 删除链表中倒数第n个节点
- JAVA的输入输出流解析
- 动态数组-2015-7-21(简单题)
- ASP.NET GridView 自增編號
- 学习笔记
- 【LeetCode-面试算法经典-Java实现】【018-4Sum(四个数的和)】
- 【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
- PART5 测试人员经历的一个迭代
- iOS调用分类时异常unrecognized selector sent to class
- 【LeetCode-面试算法经典-Java实现】【020-Valid Parentheses(括号验证)】
- LeetCode 题解(147): Lowest Common Ancestor of a Binary Tree
- Linux VLAN框架及其在Intel网卡I350的实现
- hadoop学习笔记之HDFS
- maven 在编译的时候跳过 test junit的写法
- 对安徽省高等学院计算机教育研究会的一次简单渗透。