剑指offer66题--Java实现,c++实现和python实现 14.链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

C++实现

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/

class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if(pListHead==NULL||k==0)
            return NULL;
        ListNode*pTail=pListHead,*pHead=pListHead;
        for(int i=1;i<k;++i)
        {
            if(pHead->next!=NULL)
                pHead=pHead->next;
            else
                return NULL;
        }
        while(pHead->next!=NULL)
        {
            pHead=pHead->next;
            pTail=pTail->next;
        }
        return pTail;
    }
};

Java实现

/*
public class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null||k==0){
            return null;//如果链表为空,或者输出倒数第0个节点,就直接返回null
        }
        ListNode p1=head;
        for(int i=0;i<k-1;i++){
            if(p1.next!=null){
                p1=p1.next;
            }else{
                return null;//没有倒数第k个节点,则返回null
            }
        }
        ListNode p2=head;
        while(p1.next!=null){//存在倒数第k个节点
            p1=p1.next;
            p2=p2.next;
        }
        return p2;
    }
}

python实现

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindKthToTail(self, head, k):
        if not head or not k:
            return None
        left, right = head, head
        for i in range(k - 1):
            if not right.next:
                return None
            right = right.next
        while right.next:
            left = left.next
            right = right.next
        return left

猜你喜欢

转载自blog.csdn.net/walter7/article/details/85260917