给定一个链表,删除链表的倒数第n个节点并返回链表的头指针
例如,
给出的链表为:1->2->3->4->5, n= 2.
删除了链表的倒数第n个节点之后,链表变为1->2->3->5.
备注:
题目保证n一定是有效的
请给出请给出时间复杂度为\ O(n) O(n)的算法
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
function removeNthFromEnd( head , n ) {
// write code here
if(head.next == null || head == null) {
head = null
return head
}
var top = {}
top.next = head
var cur1 = top
var cur2 = top
while(n){
cur2 = cur2.next
n--
}
while(cur2.next){
cur1 = cur1.next
cur2 = cur2.next
}
cur1.next = cur1.next.next
return top.next
}
module.exports = {
removeNthFromEnd : removeNthFromEnd
};
京公网安备 11010502036488号