Reverse Linked List

2024. 11. 7. 14:55알고리즘/Leetcode

반응형

Solution

Given the head of a singly linked list, reverse the list, and return the reversed list.

 

Examples

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

 

Example 2:

Input: head = [1,2]
Output: [2,1]

 

Example 3:

Input: head = []
Output: []

 

Explanation

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode newNode = null;
        while(head != null){
            ListNode next = head.next;
            head.next = newNode;
            newNode = head;
            head = next;
        }
        return newNode;
    }
}

 

newNode: It will become the new head of the reversed list. Initially, it is set to null because the end of the reversed list should point to null.

 

The while loop

1. Save the Next Node

- The next variable saves the current node's next pointer so that we don't lose track of the rest of the list after reversing the link.

 

2. Reverse the Pointer

- This step reverses the direction of the next pointer for the head node, making it point to newNode

 

3. Update newNode

- Move newNode to the current head node, marking it as the new head of the reversed list.

 

4. Advance the Head

- Finally, move head to next, the next node in the original list, to continue the process.

 

Return newNode, which is the head of the reversed list.

반응형

'알고리즘 > Leetcode' 카테고리의 다른 글

Palindrome Linked List  (1) 2024.11.11
Merge Two Sorted Lists  (2) 2024.11.08
Remove Nth Node From End of List  (4) 2024.11.06
Delete Node in a Linked List  (0) 2024.10.25
String to Integer (atoi)  (2) 2024.10.22