Remove Nth Node From End of List (M)
題目
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
題意
給定一個鏈表,洗掉倒數第n個結點,
思路
One Pass方法:先將一個指標移動到正數第n個結點處,這時再建一個指標指向頭結點,之后同步向后移動這兩個指標,當第一個指標到達尾結點時,第二個指標正好在倒數第n個結點處,為了進行洗掉操作,還要建一個指標保存第二個指標的前結點,要注意洗掉的正好是頭結點這種情況,
代碼實作
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int count = 1;
ListNode last = head;
while (count != n) {
last = last.next;
count++;
}
ListNode nth = head;
ListNode prev = null; // 只有當nth移動至少一次,prev才會指向具體的結點
while (last.next != null) {
last = last.next;
prev = nth;
nth = nth.next;
}
// 當prev仍為null,說明nth并沒有移動,即要洗掉的就是頭結點
if (prev == null) {
return nth.next;
}
prev.next = nth.next;
nth.next = null;
return head;
}
}
JavaScript
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function (head, n) {
let dummy = new ListNode(0, head)
let p = dummy
let count = 0
while (count < n + 1) {
p = p.next
count++
}
let q = dummy
while (p !== null) {
p = p.next
q = q.next
}
q.next = q.next.next
return dummy.next
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/43533.html
標籤:其他
上一篇:0018. 4Sum (M)
