Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
문제풀이:
- iterate써서 뒤집기
/**
* 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 *cur = head;
ListNode* prev = nullptr;
while(cur){
ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 142] Linked List Cycle II (0) | 2020.11.05 |
---|---|
[leetcode 208] Implement Trie (Prefix Tree) (0) | 2020.11.04 |
[leetcode 215] Kth Largest Element in an Array (0) | 2020.11.04 |
[leetcode 128] Longest Consecutive Sequence (0) | 2020.11.02 |
[leetcode 148] Sort List (0) | 2020.11.02 |
댓글