版权声明:本文为博主原创文章,未经博主允许不得转载。
难度:容易
要求:
翻转一个链表
注意事项
链表中的节点个数大于等于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;
}