leetcode#206 Reverse Linked List

정은경·2022년 6월 18일
0

알고리즘

목록 보기
93/125

1. 문제

2. 나의 풀이

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        
        cursor = head
        result_list_prev_node = None
        
        while cursor:
            # print(cursor.val, new_list_prev_node)
            next_node = cursor.next
            cursor.next = result_list_prev_node
            result_list_prev_node = cursor
            
            if next_node:
                cursor = next_node
            else:
                return cursor

3. 남의 풀이

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return head
        
        # 1. prev, current, next 초기화
        prev = None
        current = head
        next = head.next
        
        # 2. 링크드 리스트를 순회
        while True:
            if next is None:
                # current node is Head
                if current is None:
                    return current
                current.next = prev
                return current
            
            # Reverse Node 
            current.next = prev
            
            # Update prev, current, next
            prev = current
            current = next
            next = current.next
profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글