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