iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0
自我挑戰組

30天刷題大挑戰系列 第 16

第 15 天 有甚麼事先練再說( leetcode 019 )

JavaScript 解答

var removeNthFromEnd = function (head, n) {
    if (!head) return head;
    var len = 0;
    var tail = head;
    while (tail) {
        tail = tail.next;
        len++;
    }
    if (len === n) {
        return head.next;
    }

    len = len - n - 1;
    tail = head;
    while (len) {
        tail = tail.next;
        len--;
    }
    tail.next = tail.next.next;
    return head;
};

Ruby 解答

def remove_nth_from_end(head, n)
  p=r=head
  n.times{ p=p.next }
  return head.next if p==nil
  (r=r.next;p=p.next) while p.next!=nil
  r.next=r.next.next
  head
end

上一篇
第 14 天 不斷嘗試直到成功( leetcode 017 )
系列文
30天刷題大挑戰16
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言