leetcode #19 Remove Nth Node From End of List

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.
  • 題目大意
    給定一個單向鏈表,移除單向鏈表的倒數(shù)第n個。

比較簡單,我的做法是將單向鏈表變成雙向鏈表,找到最后一個,然后倒著找到倒數(shù)第n個節(jié)點并刪除。 注意一些邊界情況。

/**
 * 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;  //遍歷,使其變?yōu)殡p向鏈表
    pointer = pointer.next;
  }
  let i = 1;
  while (i < n) {
    pointer = pointer.last;  //找到倒數(shù)第n個節(jié)點
    i++;
  }
  if (pointer === head) {  // 如果是head,直接將head向后移一個指針
    head = head.next;
  } else {
    pointer.last.next = pointer.next;
  }
  return head;
};

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容