Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
来源:互联网 发布:js value 编辑:程序博客网 时间:2024/05/17 04:14
题目:
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.
分析:
1. 删除的可能是正数第一个元素,因此需要设置dummy node。
2. 设置两个指针,快指针先走n-1步,然后快慢指针一起向前移动,一次动一步。
3. 由于找到需要删除的点后需要把它前面节点的next设为要删除节点的next,所以需要记录慢指针前面的节点。
Java代码实现:
/** * 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) { if(head==null) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode fast = head; ListNode slow = head; ListNode pre = dummy; for(int i=0;i<n-1;i++) { fast = fast.next; } while(fast.next!=null) { fast = fast.next; slow = slow.next; pre = pre.next; } pre.next = slow.next; return dummy.next; }}
0 0
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- Leetcode 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个元素
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- 删除链表的倒数第n个结点 Remove Nth Node From End of List
- Remove Nth Node From End of List 删除链表的倒数第n个结点
- 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个节点
- leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
- LeetCode 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个节点- Easy +
- [leetcode] 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个节点)
- 又见01背包(01背包题目3)
- Google 软件工程师的简历建议
- 欢迎使用CSDN-markdown编辑器
- [2015/05/08] System services not available to Activities before onCreate()
- ORA-12154: TNS:could not resolve the connect identifier specified解决办法
- Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
- warning: deprecated conversion from string constant to ‘char*’
- 获取主机名与主机IP地址
- 解压缩的类库
- JSP中的各种跳转
- 在table中tr的display:block显示布局错乱问题
- 关于网络游戏防外挂的问题
- D3 scales and colors
- 克努斯-莫里斯-普拉特算法(Knuth–Morris–Pratt algorithm) c简单实现