站点工具

用户工具


<< 返回查看其他算法题

反转链表

输入一个链表,反转链表后,输出新链表的表头。

示例

输入:
{1,2,3}

返回值:
{3,2,1}

代码实现

  function reverseList(pHead) {
    let pre = next = null, cur = pHead
    while(cur) {
      next = cur.next
      cur.next = pre
      pre = cur
      cur = next
    }
    return pre
  }

原理

原理

测试

  function reverseList(pHead) {
    let pre = next = null, cur = pHead
    while(cur) {
      next = cur.next
      cur.next = pre
      pre = cur
      cur = next
    }
    return pre
  }
 
 
  class Node {
    constructor(val) {
      this.val = val
      this.next = null
    }
  }
 
  function createList(values) {
    let pHead = p = new Node(-1)
    for (let i = 0; i < values.length; i++) {
      p.next = new Node(values[i])
      p = p.next
    }
    return pHead.next
  }
 
  function showList(pHead) {
    let p = pHead
    let arr = []
    while (p) {
      arr.push(p.val)
      p = p.next
    }
    console.log(arr.join('->'))
  }
 
 
  let list = createList([1,2,3])
  showList(list)
  let list2 = reverseList(list)
  showList(list2)
admin · 2021/09/15 15:26 · 教程_算法_反转链表.txt