Remove Nth Node From End of List @ LeetCode

Source: Internet
Author: User

Package Level2; import Utility. listNode;/***** Remove Nth Node From End of List ** 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. */public class S19 {public Static void main (String [] args) {ListNode head = new ListNode (1); ListNode l2 = new ListNode (2); ListNode l3 = new ListNode (3 ); listNode l4 = new ListNode (4); ListNode l5 = new ListNode (5); head. next = l2; l2.next = l3; l3.next = l4; l4.next = l5; ListNode h = removeNthFromEnd (head, 5); h. print ();} public static ListNode removeNthFromEnd (ListNode head, int n) {if (n = 0 | head = null) {return Head;} if (n = 1 & head. next = null) {return null;} ListNode p = head, q = head; // Let p first q n positions for (int I = 0; I <n; I ++) {if (p! = Null) {p = p. next;} else {return head ;}// if p is already null at this time, it indicates that the deleted header must be if (p = null) {head = head. next; return head;} // p and q move forward together while (p. next! = Null) {q = q. next; p = p. next;} // Delete the element q. next = q. next. next; return head ;}}

 

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.