LintCode Remove Nth Node From End of List 刪除連結串列中倒數第n個節點
阿新 • • 發佈:2019-02-17
給定一個連結串列,刪除連結串列中倒數第n個節點,返回連結串列的頭節點。
Given a linked list, remove the nth node from the end of list and return its head.
樣例
給出連結串列1->2->3->4->5->null和 n = 2.
刪除倒數第二個節點之後,這個連結串列將變成1->2->3->5->null.
Example
Given linked list: 1->2->3->4->5->null, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5->null.
注意
連結串列中的節點個數大於等於n
Note
The minimum number of nodes in list is n.
挑戰
O(n)時間複雜度
Challenge
O(n) time
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode removeNthFromEnd(ListNode head, int n) {
if(n == 0)return head;
ListNode p = head, q = head;
while (n > 0 && null != p.next) {
p = p.next;
n--;
}
if(n > 0) {
head = head.next;
return head;
}
while(null != p.next) {
p = p.next;
q = q.next;
}
q.next = q.next.next;
return head;
}
}