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

LeetCode题解:206. 反转链表,JavaScript,While循环迭代,详细注释 #109

Open
chencl1986 opened this issue Jul 25, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

chencl1986 commented Jul 25, 2020

原题链接:https://leetcode-cn.com/problems/reverse-linked-list/

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

我们需要在遍历旧链表时,将节点1赋值给新链表,再将下一个节点2的next指向新链表中的节点1即可。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function (head) {
  // 存储翻转后的链表节点
  let reversedNode = null;
  // 存储原链表的节点
  let originalNode = head;

  // 遍历原链表,完成遍历后退出
  while (originalNode) {
    // 临时存储当前链表指向的下一个节点,、
    const tempNode = originalNode.next;
    // 将原链表的指针指向翻转后的链表节点
    originalNode.next = reversedNode;
    // 将原链表节点赋值给翻转后的链表节点
    reversedNode = originalNode;
    // 将下一个节点赋值给原节点,继续循环实现遍历
    originalNode = tempNode;
  }

  return reversedNode;
};
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