Remove Nth Node from End of List Leetcode Java

Source: Internet
Author: User

Describe
Given A linked list, remove the N
Th node from the end of a list and return its head.
For example, Given linked list:1->2->3->4->5, and n = 2.
Aer 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.
Analysis
Code

1  Public StaticListNode Removenthnodefromend (ListNode head,intN) {2         if(Head = =NULL|| n = = 0)3             returnhead;4ListNode fast = head, slow = head, p =head;5         intLen = 1;6          while(P.next! =NULL) {7p =P.next;8len++;9         }Ten         if(n = =Len) { One             returnHead.next; A         } -n = n%Len; -          for(inti = 0; I < len-n-1; i++) { theFast = Fast.next;//fast will go 1 more than I -         } -slow =Fast.next; -Fast.next =Slow.next; +         returnhead; -}

Remove Nth Node from End of List Leetcode 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.