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

反转链表 206 #38

Open
sl1673495 opened this issue May 23, 2020 · 0 comments
Open

反转链表 206 #38

sl1673495 opened this issue May 23, 2020 · 0 comments
Labels

Comments

@sl1673495
Copy link
Owner

sl1673495 commented May 23, 2020

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

记录一个 next 表示下一个节点, cur 表示当前节点,prev 表示上一个节点, 在循环中不断的把 cur.next 赋值为 prev,然后 cur 前进为刚刚保存的 next 节点,直到 cur 为 null。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
let reverseList = function (head) {
  let prev = null
  let cur = head

  while (cur) {
    let next = cur.next
    cur.next = prev
    prev = cur
    cur = next
  }

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

No branches or pull requests

1 participant