Leetcode: Remove Nth Node From End of List
来源:互联网 发布:江苏省人工智能会议 编辑:程序博客网 时间:2024/05/16 19:49
Problem:
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.
Solution:
Main Idea:
n + length - n = length;
So if we have to pointers, p1 and p2. all are in front of the head;
Then if we, let the first pointer p1 move right n steps. Then it has length - n steps to reach the end.
So if then we let the p1 and p2 all move right. When p1 reaches the end, p2 will also have moved length - n steps. So p2 has n steps to go to reach the end. So we can find the node we want using p2.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null || n == 0) { return head; } ListNode newHead = new ListNode(0); newHead.next = head; ListNode p1 = newHead; ListNode p2 = newHead; while (p1.next != null && n > 0) { p1 = p1.next; n--; } if (n != 0) return head; while (p1.next != null) { p1 = p1.next; p2 = p2.next; } if (p2.next.next == null) { p2.next = null; } else { ListNode next = p2.next.next; p2.next = next; } return newHead.next; }}
0 0
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- 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: Remove Nth Node From End of List
- leetcode 40: 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] Remove Nth Node From End of List
- [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 - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- leetcode之Remove Nth Node From End of List
- 果 的大数据问题
- Leetcode:Letter Combinations of a Phone Number
- C#的130个面試題目大全
- 浮世录----序言
- 【Jason's_ACM_解题报告】Oil Deposits
- Leetcode: Remove Nth Node From End of List
- 读《死于技术 索尼衰亡启示》
- 【Jason's_ACM_解题报告】Ancient Messages
- 【Jason's_ACM_解题报告】Abbott’s Revenge
- 抛开rails使用ActiveRecord连接数据库
- 【Jason's_ACM_解题报告】Ordering Tasks
- windows程序设计中10-3 POEPOEM程序无法运行
- 【Jason's_ACM_解题报告】Play on Words
- 欢迎使用CSDN-markdown编辑器