관리 메뉴

솜씨좋은장씨

[leetCode] 206. Reverse Linked List (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 206. Reverse Linked List (Python)

솜씨좋은장씨 2020. 10. 22. 23:40
728x90
반응형

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?

 

Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        my_list = []
        answerList = None
        
        while head != None:
            val = head.val
            
            my_list.append(val)
            
            head = head.next
            
        my_list_reverse = my_list[::-1]
        
        for i in range(len(my_list_reverse)):
            if i == 0:
                answerList = ListNode(my_list_reverse[i])
            else:
                new_node = ListNode(my_list_reverse[i])
                currNode = answerList
                while currNode.next != None:
                    currNode = currNode.next
                    
                currNode.next = new_node
        return answerList
        

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments