Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

反转链表

Sunny-117 opened this issue · comments

commented
反转链表
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let prev = null; //前节点
    let cur = head; //当前节点
    while(cur){
        const next = cur.next; //后节点 
        cur.next = prev; //当前节点的下一个节点指向前节点
        prev = cur; //前节点向后移动
        cur = next //当前节点向后移动
    }
    return prev; //到这里prev指向原链表的最后一个节点
};
commented

题目链接:https://leetcode.cn/problems/reverse-linked-list
时间复杂度:O(n)
空间复杂度:O(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}
 */
var reverseList = function(head) {
   if(head==null) return head;
   let node=null;
   while(head)
   {
       let next=head.next;
       head.next=node;
       node=head;
       if(next) head=next;
       else break;
   }
   return head;
};