王廷瑋|數位醫療|智慧醫療: 206. Reverse Linked List WFU

2024年7月17日 星期三

206. Reverse Linked List

206. Reverse Linked List


給定單向鏈表的頭節點,反轉鏈表並返回反轉後的鏈表。

範例:

輸入:head = [1,2,3,4,5]
輸出:[5,4,3,2,1]


Python


# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Initialize previous node to None
prev = None
current = head
while current:
# Temporarily store the next node
next_node = current.next
# Reverse the current node's pointer
current.next = prev
# Move pointers one position ahead
prev = current
current = next_node
# Return the new head of the reversed list
return prev

17.64MB, 43ms


C++


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* current = head;
while (current != nullptr) {
ListNode* next_node = current->next; // Temporarily store the next node
current->next = prev; // Reverse the current node's pointer
prev = current; // Move pointers one position ahead
current = next_node;
}
return prev; // New head of the reversed list
}
};

13.05MB, 8ms


Javascript


/**
* 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) {
let prev = null;
let current = head;
while (current !== null) {
let nextNode = current.next; // Temporarily store the next node
current.next = prev; // Reverse the current node's pointer
prev = current; // Move pointers one position ahead
current = nextNode;
}
return prev; // New head of the reversed list
};

51.74MB, 61ms