1. 程式人生 > >劍指offer66題--Java實現,c++實現和python實現 14.連結串列中倒數第k個結點

劍指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