Topic:
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.
Translation:
Give you a list of the last nth nodes to remove.
Ideas:
The difficulty of this problem is also OK, is some of the details of the aspect, the first possible link list on a node. The second possibility is that the first node is deleted. The last is the connection to the node after the node is deleted.
Code:
Public ListNode Removenthfromend (listnode head, int n) { if (head==null| | (Head.next = = null && n ==1)) return null; ListNode p = head; ListNode q = head; ListNode pre = head; while (n!=1) { q = q.next; n--; } while (Q.next!=null) { pre = P; Q = q.next; p = p.next; } if (Pre.next = = p.next) head = Head.next; else pre.next = P.next; return head; }
I used the method is two pointer p,q,q first traverse to the position of n-1, and then the two pointers traverse backwards at the same time, until Q to the end, at this time p should be deleted. At the same time, a pointer points to the previous one of P.
If P and pre point to the same node, the first element is deleted at this point. Because of the last q.next==null, this is as long as the head node points to his next point.
If P and pre are not equal, the P is deleted directly
Leetcode remove Nth node from End of List removes the last n nodes