티스토리 뷰
1. 문제
문제:https://leetcode.com/problems/reverse-linked-list/
문제는 간단하게 이해되고 쉽게 풀리는 문제. reverse linked list 만드는거임. iterative하게 recursive하게 두 방법 모두로 풀린다.
근데, 파이썬 다중할당에 대해 이해하지 못하고 있다가 iterative way로 풀 때 자꾸 에러가 나서 기억하기 위해 포스팅.
1.1 Recursive way
# 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:
# SOL 1) Recursive Way
def reversef(node,prev=None):
if not node:
# node가 비어있는 경우
return prev
next, node.next = node.next, prev
return reversef(next,node)
return reversef(head)
1->2->3->4->5의 예를 생각해보자. 그럼 순서대로 코드의 수행결과는 다음과 같이 된다.
# 1) node로 1, prev로 None이 들어온 경우
# next = 2
# node.next = None
# node = 1
# 2) node로 2, prev로 1이 들어온 경우
# next= 3
# node.next= 1
# node = 2
# ....
# 5) node로 5, prev로 4가 들어온 경우
# next = None
# node.next = 4
# node = 5
# 6) node로 None, prev로 5가 들어온 경우
# 5가 반환.
# 마지막을 5로 반환하므로 5->4->3->2->1->None의 head를 반환하게 되는 셈
별로 어려운 방법은 아님.
1.2 Iterative Way
이것도 생각 자체는 어렵지 않다. list를 처음부터 순회하며 화살표의 방향만 바꿔주는 것이 핵심 idea.
# 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:
# SOL 2) Iterative Way
# prev 정의
prev= None
while head:
'''WRONG WAY!
prev,head,head.next = head,head.next,prev
'''
next,head.next = head.next,prev
prev,head = head,next
return prev
다만 주의해서 봐야하는 부분은
next,head.next = head.next,prev
prev,head = head,next
이걸 하는 부분. 여기서 맨 처음에는
prev,head,head.next = head,head.next,prev
이렇게 시도했는데 안 되었음. 그이유는 밑과 같음.
2. 파이썬의 다중할당
파이썬의 다중할당은 우변의 값을 선 평가한 다음 좌변에 변수 순서에 대응하여 대입함. 즉,
a,b,c = d,e,f
는 def의 값을 먼저 다 평가한 담에
a=d
b=e
c=f
이 순서대로 진행함. 동시에 갖다 박는게 아님.
따라서 위에서 prev,head,head.next = head,head.next,prev
가 안 된 이유는
head를 head.next로 바꿔서 진전시켜놨더니 head.next를 prev로 바꾸니까 안되는거임.
'기초 알고리즘 문제 풀이' 카테고리의 다른 글
# 파이썬 객체 특성과 깊은 복사. 문풀시 기억하기. (2) | 2020.08.18 |
---|---|
42. UVa-11057 Exact Sum // given v, find (a,b) s.t. a+b=v (0) | 2020.03.05 |
41. UVa-10567 //Binary Search (0) | 2020.03.04 |
40. UVa-10576 Y2K Accounting Bug (0) | 2020.03.03 |
39. UVa-01047 Zones, <TLE> (0) | 2020.03.02 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 영상구조
- 영상처리
- 이미지
- 이미지처리
- Andrew ng
- 신경망
- Neural Network
- 연속 신호
- RGB이미지
- Logistic Regression
- 밑바닥부터 시작하는 딥러닝
- 순환 신경망
- 매트랩
- 매트랩 함수
- 딥러닝
- 머신 러닝
- 신호 및 시스템
- 이산 신호
- 사진구조
- 자연어 처리
- rnn
- 컴퓨터과학
- NLP
- CS
- ML
- 컴퓨터 과학
- gradient descent
- CNN
- 머신러닝
- 인덱스 이미지
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함