Address: https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
Given a linked list, removeNTh 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:
GivenNWill always be valid.
Try to do this in one pass.
In fact, the question requires that the records can be stored only once, and the validity of the N value is not required. The simplest way is to traverse and obtain the number of linked list nodes, and then delete the specified node. However, this requires two successive links.
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null){ return null; } ListNode countList = head; int ListCount = 0; while(countList!=null){ ListCount++; countList = countList.next; } if(ListCount-n==0){ return head.next; } ListNode ans = head; int count = 0; ListNode pre = null; ListNode cur = null; while(head.next!=null){ count++; pre = head; cur = head.next; if(count == ListCount-n){ pre.next = cur.next; break; } head = head.next; } return ans; }}
There is a way you only need to traverse a linked list, see: http://blog.csdn.net/huruzun/article/details/22047381
Public class solution {public listnode removenthfromend (listnode head, int N) {listnode pre = NULL; listnode ahead = head; listnode behind = head; // The ahead node takes n-1 first, behind and ahead walk together. When ahead arrives at the last node, behind is the element to be deleted for (INT I = 0; I <n-1; I ++) {If (ahead. next! = NULL) {ahead = ahead. Next;} else {return NULL ;}} while (ahead. Next! = NULL) {pre = behind; behind = behind. next; ahead = ahead. next;} // If the header node is deleted, if (pre = NULL) {return behind. next;} else {pre. next = behind. next;} return head ;}}
I personally think that there is not much optimization in the second method, just to meet the question requirements. However, this method can be used to solve many linked list problems. For example, finding the intersection nodes of two linked lists can also be solved through this similar distance relationship.
Remove nth node from end of list