[Leetcode] 19. Remove Nth Node from End of List Java

Source: Internet
Author: User

Title: Given A linked list, remove the nth node from the end of the list and return its head.

For example,

   n = 2.   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n would always be valid.
Try to do the in one pass.

test instructions and analysis: The first thing I do is to iterate through the length, then the length minus n will know to delete the positive number of elements, not meet the requirements, because only one time, so only with two pointers, a fast pointer to go first n step, a slow pointer from the beginning, so when the fast pointer to the tail, The slow pointer refers to the first element of the element to be deleted.

Code:

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/classSolution { PublicListNode Removenthfromend (ListNode head,intN) {if(Head = =NULL)return NULL; ListNode Fast= head;//because it can only be traversed once, so can only use two pointers, a fast pointer to go first n, a slow pointer from the beginning, so when the fast pointer to the tail, the slow pointer is to delete the element's previous element. ListNode low =Head;  for(inti=0;i<n;i++) {Fast=Fast.next; }        if(Fast = =NULL) {Head=Head.next; returnHead; }                 while(Fast.next! =NULL) { low=Low.next; Fast=Fast.next; } Low.next=Low.next.next; returnHead; }}

[Leetcode] 19. Remove Nth Node from End of List Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.