프로그래밍/알고리즘 문제풀이
codewar: Fun with lists:indexOf
noveljava
2019. 6. 25. 12:00
문제
- https://www.codewars.com/kata/581c6b075cfa83852700021f
Codewars: Train your coding skills
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
문제풀이
- 주어진 node를 순회하면서, 찾고자하는 value의 위치를 찾는 문제입니다.
- while을 통해서 head가 null 인지를 판별하고, null 이 아니라면 순회를 시작하게 됩니다.
- 해당 index의 data 와 같다면, 해당 index 값을 전달 해주고
- 그렇지 않다면, head를 다음 node로 변경을 합니다.
- 끝까지 순회를 ( head가 null 로 설정이 됨 ) 하였다면, 찾고자하는 값이 없으므로 -1 를 return 시켜줍니다.
class Solution {
static int indexOf(Node head, Object value) {
int idx = -1;
while( null != head ) {
idx++;
if(head.data == value) {
break;
} else {
head = head.next;
}
}
if( null == head ) {
idx = -1;
}
return idx;
}
}