본문 바로가기

알고리즘/해커랭크

[해커랭크] Get Node Value

문제링크 : www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail/problem

 

Get Node Value | HackerRank

Given the head of a linked list, get the value of the node at a given position when counting backwards from the tail.

www.hackerrank.com

두 번 반복하는 것밖에 안떠올랐다. 

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;
}