Today, I solved the Reverse Linked List.
Description:
In this problem, we reverse the order of single linked list.
My idea was that changing the pointer to make reverse order. So, I thought I should change like this "1->2" as a "2->1" repeatedly. In the description of the question, we can see "A linked list can be reversed either iteratively or recursively."
I'm not sure about this kind of question with python. Here is solution for this problem.
Solution1(Iteractive Method):
In iteractive method, we use the three variable: prev, curr and head. First, we declare prev as None(empty).
We use loop to run this code until 'head' points to None (the next of 5 in this case!) Below the code, I made the description of method as comments.
- The first head is '1', so we make curr points to head
- head moves to next, so now 2 is head.
- curr.next points to prev, so it is None
- Now prev points to '1'!
This method, we move our head and prev. curr is the temporary variable to change the pointer of head and prev!
Now, we are gonna look another method using recursion.
Solution2(Recursive Method):
For recursion function, I put one more parameter prev in reverseList(). Same with Iteractive method, we are gonna end up the recursion when head points to None. That's why I put "if not head return prev." Algorithms is also same with iteractive method.
- curr points to the head next (point 2 in the first case)
- The next node of head is gonna be prev (point None in the first case)
- Finally, we pass curr, head recursively (curr = 2, head = 1 in ths first case)
- Now, new head would be curr, and new prev would be head (new head =2, prev = 1 after the first case)
'LeetCode 🏔️ > Linked List' 카테고리의 다른 글
23. Merge k Sorted Lists (0) | 2023.05.01 |
---|---|
141. Linked List Cycle (0) | 2023.05.01 |
143. Reorder List (0) | 2023.04.25 |
19. Remove Nth Node From End of List (1) | 2023.04.23 |
21. Merge Two Sorted Lists (0) | 2023.04.10 |