Remove Nth Node From End of List
2013-10-16 08:05
337 查看
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
也可以用双指针(fast pointer) 来做,但是要注意 n = len的情况。
第二遍:
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.
也可以用双指针(fast pointer) 来做,但是要注意 n = len的情况。
/** * 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) { // Note: The Solution object is instantiated only once and is reused by each test case. ListNode per = head; ListNode cur = head; ListNode before = head; int len = 0; while(per != null){ per = per.next; len ++; } int num = len - n; if(num == 0)return head.next; else{ per = head; for(int i = 0; i < num; i ++){ cur = per; per = per.next; } cur.next = per.next; return head; } } }
第二遍:
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { // Note: The Solution object is instantiated only once and is reused by each test case. ListNode header = new ListNode(-1); header.next = head; ListNode cur = header; ListNode per = header; ListNode fast = header; for(int i = 0; i < n; i ++){ fast = fast.next; } while(fast != null){ per = cur; fast = fast.next; cur = cur.next; } per.next = cur.next; return header.next; } }
相关文章推荐
- Remove Nth Node From End of List Java
- leetcode 第一刷_Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- 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 | 19. Remove Nth Node From End of List
- Remove Nth Node From End of List
- Leetcode_19:Remove Nth Node From End of List
- Remove Nth Node From End of List
- LeetCode解题报告--Remove Nth Node From End of List
- 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)
- 19. Remove Nth Node From End of List
- Leetcode 19.Remove Nth Node From End of List
- Remove Nth Node From End of List
- 【LeetCode】19 - Remove Nth Node From End of List
- 19. Remove Nth Node From End of List