Hi,大家好,我是小庄。

明天打卡的算法题是 —— LeetCode 206.反转链表

该题将采纳「迭代法」和「递归法」别离实现

话不多说,一起来学习吧~

一、Leetcode题目

1、题目地址

点击查看Leetcode题目

2、具体题目


二、实现代码

1、思路:迭代法;

(1)具体代码

/** * Definition for singly-linked list. * function ListNode(val, next) { *     this.val = (val===undefined ? 0 : val) *     this.next = (next===undefined ? null : next) * } *//** * @param {ListNode} head * @return {ListNode} *//*    思路:迭代法;    工夫复杂度:O(n);    空间复杂度:O(1) */var reverseList = function(head) {    let pre = null;    let cur = head;    let next = head;    while(cur !== null) {        next = cur.next;        cur.next = pre;        pre = cur;        cur = next;    }    return pre;};


(2)运行后果


2、办法:递归法;

(1)具体代码

/** * Definition for singly-linked list. * function ListNode(val, next) { *     this.val = (val===undefined ? 0 : val) *     this.next = (next===undefined ? null : next) * } *//** * @param {ListNode} head * @return {ListNode} *//*    思路:递归法实现;    工夫复杂度:O(n);    空间复杂度:O(n); */var reverseList = function(head) {    if(head === null || head.next === null) {        return head;    }    let res = reverseList(head.next);    head.next.next = head;    head.next = null;    return res;};


(2)运行后果

3、补充局部

注:以下为手动构建残缺链表,并采纳迭代法实现。

function ListNode(val) {  this.val = val;  this.next = null;}function createList(n) {  let head = null;  while(n) {    let tempNode = new ListNode(n);    tempNode.next = head;    head = tempNode;    n--;  }  return head;}let head = createList(3);console.log(head);//1->2->3function getReverseList(head) {  let pre = null;  let cur = head;  let next = head;  while(cur !== null) {      next = cur.next;      cur.next = pre;      pre = cur;      cur = next;  }  return pre;}let res = getReverseList(head);console.log(res);//3->2->1

三、解说视频

点击查看B站解说视频

四、补充局部

关注公众号:【深漂程序员小庄】:
内含丰盛的学习资源和面试教训(不限前端、java),还有学习交换群可加,并且还有各大厂大佬可一起交流学习,一起提高~增加小庄微信,回复【加群】,可退出互联网技术交换群。

本文由mdnice多平台公布