LeetCode-返回倒数第 k 个节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */



int kthToLast(struct ListNode* head, int k){
     
    struct ListNode* p=head;
    struct ListNode* q=head;
    if(k<0){
     
    	return 0; 
	} 
	int count=0;
	while(count!=k){
     
		count++;
		p=p->next;
	}
	while(p){
     
		p=p->next;
		q=q->next;
	}
	return q->val;
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
     
    public int kthToLast(ListNode head, int k) {
     
        ListNode p = head;
        for(int i=0;i<k;i++){
     
          p = p.next;  
        }

        while(p != null){
     
            p = p.next;
            head = head.next;
        }

        return head.val;
    }
}

你可能感兴趣的:(LeetCode,链表,算法)