LeetCode 19 Remove Nth Node From End of List Remove the Nth Node, leetcodenth
Question:
Given a linked list, remove the nth node from the end of 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 will always be valid.
Try to do this in one pass.
Translation:
Give you a linked list and remove the nth last node.
Ideas:
The difficulty of this question is okay, that is, some details. First, the linked list may be a node. The first node may be deleted. The last step is to delete the node connection 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 am using two pointers, p, q, and q, first traverse to the n-1 position, and then both pointers traverse backward at the same time until q ends. At this time, p should be deleted. At the same time, a pointer points to the first one of p.
If p and pre point to the same node, the first element is deleted. Because the previous q. next = null, this is as long as the head node points to his next node.
If p and pre are different, delete p directly.