Leetcode notes: Remove Nth Node from End of List

Source: Internet
Author: User

I. Title Description

Given A linked list, remove the n th node from the end of the 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 would always be valid.
? Try to do the in one pass.

Two. Topic analysis

Given a linked list, it refers to the deletion of the n penultimate n node. The value of the hint here n is legal by default. But in fact, the input of the N to make an exception to judge only a few sentences.

Using two pointers, the concept of a fast/slow pointer, one of the pointers goes first n , then the slow pointer goes, and when the fast pointer goes to the end, the slow pointer goes to the previous position of the node that needs to be removed.

The main difficulty of this problem is to consider the boundary problem, as well as the special case (to remove the head node), such as input 1->2->3->4 , n=4 then need to delete 1 , at this point only the head pointer head = head->next can be.

Three. Sample code

#include <iostream>struct listnode{intValue listnode*Next; ListNode (int x): Value (x),Next(NULL) {};}; Class Solution{public:listnode*removenthfromend(ListNode*head,intN) {if(head = = NULL)returnNULL; ListNode*fast= head; ListNode*slow= head; ListNode*temp= head; for(inti =0; I < n; i++) {fast = Fast->Next;if(FAST)Continue;Else  Break; } while(FAST) {fast = Fast->Next;            temp = slow; slow = slow->Next; }if(slow = = head) {head = head->Next;returnHead } temp->Next= slow->Next;DeleteSlowreturnHead }};

Results:

Four. Summary

The actual programming often encounter boundary problems, careless errors can easily cause the program to crash, the use of pointers and linked list skills need to further study.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode notes: Remove Nth Node from End of List

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.