[Hackrank]Get Node Value

You’re given the pointer to the head node of a linked list and a specific position. Counting backwards from the tail node of the linked list, get the value of the node at the given position. A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on.

Input Format 
You have to complete the int GetNode(Node* head, int positionFromTail) method which takes two arguments - the head of the linked list and the position of the node from the tail. positionFromTail will be at least 0 and less than the number of nodes in the list. You should NOT read any input from stdin/console.

Constraints 
Position will be a valid element in linked list.

Output Format 
Find the node at the given position counting backwards from the tail. Then return the data contained in this node. Do NOT print anything to stdout/console.

Sample Input

1 -> 3 -> 5 -> 6 -> NULL, positionFromTail = 0
1 -> 3 -> 5 -> 6 -> NULL, positionFromTail = 2

Sample Output

6

3

题意:其实这道题要求的就是linkedlist倒数位置的node的值,虽然说了一大推但其实实际没有变。

解题思路:linkedlist不能像数组那样直接取,所以我们要根据他的特点来设计解决方法,我们可以这样思考,既然要求倒数的值,那也就是说从头开始就要走n-k的步数。那么你当然可以先遍历一遍这个linkedlist,得到长度,再走到那个节点去算这个值。还有一种只需要走一遍的方法是,设定两个指针,都等于head,快的那个先走k步,走到k步后,两个指针一起走,等到快指针走到尾部的时候,正好走了n-k步,于是就相当于慢指针走了n-k步,所以slow停下来的节点就是我们需要的节点

/*
  Get Nth element from the end in a linked list of integers
  Number of elements in the list will always be greater than N.
  Node is defined as 
  class Node {
     int data;
     Node next;
  }
*/
    
int GetNode(Node head,int n) {
     // This is a "method-only" submission. 
     // You only need to complete this method.
    //快慢指针
    Node slow=head;
    Node fast=head;
   //快的先走
    for(int i=0;i<n;i++){
        fast=fast.next;
    }
    //一起走
    while(fast.next!=null){
        slow=slow.next;
        fast=fast.next;
    }
    return slow.data;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值