문제링크 : www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail/problem
두 번 반복하는 것밖에 안떠올랐다.
N번 반복해서 해결하는 코드가 있을 줄 알고 다른 사람풀이를 확인해보니 역시 있었다.
-내 코드
static int getNode(SinglyLinkedListNode head, int positionFromTail) {
int nodeCnt =0;
SinglyLinkedListNode key = head;
while(key!=null){
nodeCnt++;
key= key.next;
}
for(int i=0;i<nodeCnt-1-positionFromTail;i++){
head = head.next;
}
return head.data;
}
- 좋은 풀이
int GetNode(Node *head,int positionFromTail)
{
int index = 0;
Node* current = head;
Node* result = head;
while(current!=NULL)
{
current=current->next;
if (index++>positionFromTail)
{
result=result->next;
}
}
return result->data;
}
'알고리즘 > 해커랭크' 카테고리의 다른 글
[해커랭크] Delete duplicate-value nodes from a sorted linked list (0) | 2021.01.14 |
---|---|
[해커랭크] Merge two sorted linked lists (0) | 2021.01.14 |
[해커랭크] Compare two linked lists (0) | 2021.01.13 |
[해커랭크] Reverse a linked list (0) | 2021.01.13 |
[해커랭크] Print in Reverse (0) | 2021.01.13 |