[LeetCode/206/Java]Reverse Linked List
풀이
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if((head == null) || (head.next == null)) return head;
ListNode result = null;
ListNode buf = head;
ListNode foward = head;
while(buf != null) {
foward = foward.next; // head
buf.next = result; // result
result = buf; // result
buf = foward; // head
}
return result;
}
}
후기
LinkedList의 노드를 반전하는 알고리즘입니다.
순서를 바꿔주기 위해서 노드를 하나 더 만들고 값을 swap시켜줍니다.
time complexity O(N)
space complexity O(N)
728x90
반응형
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/70/Java]Climbing Stairs (0) | 2022.05.29 |
---|---|
[LeetCode/119/Java]Pascal's Triangle II (0) | 2022.05.29 |
[LeetCode/700/Java]Search in a Binary Search Tree (0) | 2022.05.28 |
[LeetCode/24/Java]Swap Nodes in Pairs (0) | 2022.05.28 |
[LeetCode/344/Java]Reverse String (0) | 2022.05.28 |