Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

链表常用思路 #95

Open
lovelmh13 opened this issue Jul 1, 2021 · 0 comments
Open

链表常用思路 #95

lovelmh13 opened this issue Jul 1, 2021 · 0 comments

Comments

@lovelmh13
Copy link
Owner

lovelmh13 commented Jul 1, 2021

找链表的中间值

用快慢指针

function findMid (head) {
  let slow = head
  let fast = head
  while (fast.next && fast.next.next) {
    slow = slow.next
    fast = fast.next.next
  }
  const newHead = slow.next // 后半段拆出来
  slow.next = null // 将链表切断,把前半段拆出来
  return newHead // 后半段是 newHead,前半段是 head
}

反转链表

画个图就懂了

function reverseList (head) {
  let initHead = head
  let pre = head

  while (initHead && initHead.next) {
    const node = initHead.next
    initHead.next = initHead.next.next
    node.next = pre
    pre = node
  }
  return pre
}

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant