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

反转链表 #285

Open
Sunny-117 opened this issue Nov 8, 2022 · 2 comments
Open

反转链表 #285

Sunny-117 opened this issue Nov 8, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@lxy-Jason
Copy link
Contributor

/**
 * @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指向原链表的最后一个节点
};

@Pcjmy
Copy link
Contributor

Pcjmy commented Feb 26, 2023

题目链接: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;
};

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

3 participants