美文网首页
leetcode #19 Remove Nth Node Fro

leetcode #19 Remove Nth Node Fro

作者: huntriver | 来源:发表于2017-09-16 19:11 被阅读0次

Given a linked list, remove the nth node from the end of list and return its head.
Note: The solution set must not contain duplicate quadruplets.

For 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.
  • 题目大意
    给定一个单向链表,移除单向链表的倒数第n个。

比较简单,我的做法是将单向链表变成双向链表,找到最后一个,然后倒着找到倒数第n个节点并删除。 注意一些边界情况。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
const removeNthFromEnd = function (head, n) {
  let pointer = head;
  while (pointer.next) {  
    pointer.next.last = pointer;  //遍历,使其变为双向链表
    pointer = pointer.next;
  }
  let i = 1;
  while (i < n) {
    pointer = pointer.last;  //找到倒数第n个节点
    i++;
  }
  if (pointer === head) {  // 如果是head,直接将head向后移一个指针
    head = head.next;
  } else {
    pointer.last.next = pointer.next;
  }
  return head;
};

相关文章

网友评论

      本文标题:leetcode #19 Remove Nth Node Fro

      本文链接:https://www.haomeiwen.com/subject/nhdusxtx.html