Given A linked list, remove the nth node from the end of the list and return its head.
For example,
1->2->3->4->5 N = 2. 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
The topic is to delete the node from the tail node n
The first is to find the node
Define two pointer p,q, two pointers to head node
The P-pointer goes first n steps, then two pointers go together, and the yourselves walk to the end of the hand, then the pointer after walking is just a distance from the tail node n
also save the previous node of the Q pointer, also note that if the deleted node is the head node , at which point the previous node of the Q node is not
The code is as follows:
<span style= "FONT-SIZE:18PX;" >/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode *removenthfromend (listnode *head, int n) { listnode *p,*q;//define P q,p go first n step, then p Q to traverse backwards at the same time, When P goes to the end, Q is at the bottom of the p=head; Q=head; while (n>0) { p=p->next; --n; } ListNode *pur=null;//is used to hold the previous node of the last nth node while (P!=null) { pur=q; q=q->next; p=p->next; } if (pur==null)//indicates that the first node to be deleted is head change head { head=q->next; Delete q; } else{ pur->next=q->next; Delete q; } return head; }; </span>
Remove Nth Node from End of List Leetcode