19. Remove Nth Node From End of List
原題目
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.
翻譯
給定一個鏈表,刪除倒數第n個節點,然後返回這鏈表的頭部。
比如:
給定鏈表: 1->2->3->4->5, n = 2. 從尾部移除第2個節點, 然後鏈表變爲: 1->2->3->5.
注意:給定的n總是有效的,嘗試一次通過。
解題思路
建立一前一後兩個節點:firstLn, secondLn.
初始化firstLn的next 指向鏈表頭部,secondLn指向鏈表頭部
先將firstLn移動n個位置,然後開始移動SecondLn節點。
當FirstLn移動到鏈表結尾後,此時需要將SecondLn的下一個節點移除即可。
時間複雜度爲:O(n);
空間複雜度爲:O(1);
代碼示例-Java
public ListNode removeNthFromEnd(ListNode head, int n) {
if (n == 0 || head == null){
return head;
}
ListNode firstLn = head;
ListNode secondLn = new ListNode(0);
int pos = 1;
while (firstNextLn != null){
if (pos == n){
secondNextLn.next = head;
}else if (pos > n){
secondNextLn = secondNextLn.next;
}
firstNextLn = firstNextLn.next;
pos++;
}
if (secondNextLn != null){
if (secondNextLn.next.equals(head)){
return head.next;
}else{
secondNextLn.next = secondNextLn.next.next;
}
}
return head;
}