12.链表中倒数第k个结点

来源:互联网 发布:手机mac地址全为0 编辑:程序博客网 时间:2024/06/06 10:39
链表中倒数第k个结点
  • 参与人数:5703时间限制:1秒空间限制:32768K
  • 本题知识点: 链表
  •  算法知识视频讲解

题目描述

输入一个链表,输出该链表中倒数第k个结点。
设置两个指针p1和p2,p1不断向前走,当p1到链表头部的距离大于k时p2开始向前走,控制两个指针的距离为k。
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stack>using namespace::std;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 || k < 0) return NULL;ListNode *p1 = pListHead;ListNode *p2 = pListHead;int count = 0;while (p1) {count++;if (count > k) {p2 = p2->next;}p1 = p1->next;}return count >= k ? p2 : NULL;}};int _tmain(int argc, _TCHAR* argv[]){ListNode n1(1);ListNode n2(2);ListNode n3(3);ListNode n4(4);ListNode n5(5);n1.next = &n2;n2.next = &n3;n3.next = &n4;n4.next = &n5;Solution s;s.FindKthToTail(&n1, 1);return 0;}

第二次做:
/*struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};*/class Solution {public:    ListNode* FindKthToTail(ListNode* pHead, unsigned int k) {    if ( pHead == NULL || k <= 0 ) return NULL ;                int length = 0 ;        ListNode* pNode = pHead ;                while ( pNode != NULL ) {            ++ length ;            pNode = pNode -> next ;        }                if ( k > length ) return NULL ;                int cur = length - k ;        pNode = pHead ;        for ( int i = 0; i < cur; ++ i ) {            pNode = pNode -> next ;        }                return pNode ;    }};

第三次做:
/*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 ) return NULL ;                int length = 0 ;        ListNode* pNode = pListHead ;        while ( pNode != NULL ) {            ++ length ;            pNode = pNode->next ;        }                if ( k > length ) return NULL ;                int step = length - k ;        pNode = pListHead ;        for ( int i = 0; i < step; ++ i ) {            pNode = pNode->next ;        }                return pNode ;    }};


0 0