版權聲明:本文為博主原創文章,未經博主允許不得轉載。
難度:容易
要求:
翻轉一個鏈表
注意事項
鏈表中的節點個數大于等于n
樣例
給出鏈表1->2->3->4->5->null和 n = 2.刪除倒數第二個節點之后,這個鏈表將變成1->2->3->5->null.
思路:
/**
* @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(head == null){
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
for(int i = 0; i < n; i++){
if(head == null){
return null;
}
head = head.next;
}
ListNode preDel = dummy;
while(head != null){
head = head.next;
preDel = preDel.next;
}
preDel.next = preDel.next.next;
return dummy.next;
}