Delete the nth node in the linked list

Source: Internet
Author: User

1. Given a linked list, delete the nth node in the list and return the head node of the linked list.

Give the list 1->2->3->4->5->null and n = 2.

After you delete the second-to-last node, the list becomes 1->2->3->5->null.

Note

The number of nodes in the list is greater than or equal to n

challenges

O (n) Time complexity

Problem-solving ideas: Just beginning to see the last nth node, can not help feeling if it is an array to directly upside down. But for the linked list, be sure to think of the most common method---fast and slow pointer. Set a fast and slow pointer, a fast pointer to the N-step, then the speed of the pointer to go together, when the fast==null, the slow pointer is the value of the bottom nth, and then delete the line.

1 /**2 * Definition for ListNode.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int val) {7 * This.val = val;8 * this.next = null;9  *     }Ten  * } One  */  A  Public classSolution { -     /** -      * @paramhead:the first node of linked list. the      * @paramn:an Integer. -      * @return: The head of linked list. -      */ -ListNode Removenthfromend (ListNode head,intN) { +         //Write your code here -ListNode fast=head; +ListNode result =NewListNode (0); AResult.next =head; at          for(inti=0;i<n-1;i++){ -Fast =Fast.next; -         } -ListNode now =result; -          while(Fast.next! =NULL){ -Fast =Fast.next; innow =Now.next; -         } toNow.next =Now.next.next; +         returnResult.next; -     } the}

Delete the nth node in the linked list

Related Article

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.