본문 바로가기

알고리즘/LeetCode

[LeetCode/206/Java]Reverse Linked List

[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
반응형