Lintcode Delete the nth node in a linked list

Source: Internet
Author: User
Tags lintcode

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

Sample Example

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.

Analysis: Considering the robustness of each case, it is necessary to consider the tail node, especially when the tail node is deleted.

/** * Definition of ListNode * class ListNode {* Public: * int val; * ListNode *next; * ListNode (int val) {* This->val = val; * This->next = NULL;     *} *} */class Solution {public:/** * @param head:the first node of the linked list.     * @param n:an Integer.     * @return: The head of linked list. */ListNode *removenthfromend (listnode *head, int n) {//write your code here if (head==null) Retu        RN 0;        if (head->next==null&&n==1) return 0;        ListNode *p1=head;        ListNode *p2=null;        ListNode *pre=null;            for (int i=0;i<n-1;i++) {if (p1->next!=null) {p1=p1->next;        } else return NULL;        } P2=head;            while (p1->next!=null) {p1=p1->next;            PRE=P2;        p2=p2->next; } if (p2->next==null) {Pre->neXt=null;            Delete P2;        P2=null;            } else {ListNode *p3=p2->next;            p2->val=p3->val;            p2->next=p3->next;            Delete P3;        P3=null;    } return head; }};

  

Lintcode Delete the nth node in a linked 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.