前端常見的手寫算法問題

一 單鏈表反轉

1 迭代

function reverseLink (link) {
   if (!link.head || !link.head.next) {
      return link
   } else {
      let current = link.head
      let pre = null
      while(current) {
         const next = current.next
         current.next = pre
         pre = current
         current = next
      }
      link.head = pre
   }
}

2 遞歸

function reverseLink (link) {
   const head = link.head
   if (!head || !head.next) {
      link.head = head
      return link
   } else {
      link.head = head.next
      reverseLink(link)
      head.next.next = head
      head.next = null
   }
}

鏈表中環的檢測
兩個有序的鏈表合併
刪除鏈表倒數第 n 個結點
求鏈表的中間結點code

相關文章
相關標籤/搜索