码迷,mamicode.com
首页 > 其他好文 > 详细

To find the kth to Last Element of a Singly Linked List

时间:2015-07-24 22:36:18      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

To find the kth to Last Element of a Singly Linked List

None

Description

Write a pro-gram to find the kth to Last Ele-ment of a Singly Linked List
For example:
Orig-i-nal List : ->1->2->8->3->7->0->4
Out-put : 3rd Ele-ment from the end is : 7

Code - C++

  • 片段
ListNode* findkthtolast(ListNode *head, int k) {
    ListNode* runner = head;
    ListNode* chaser = head;
    if (head == NULL || k < 0) {
        return NULL;
    }
    for (int i = 0; i < k; i++) {
        runner = runner->next;
    }
    while (runner != NULL) {
        chaser = chaser->next;
        runner = runner->next;
    }
    return chaser;
}
  • 完整(包括测试)
#include<iostream>
using namespace std;
class ListNode{
public:
    int val;
    ListNode* next;
    ListNode(const int val, ListNode* nextNode = NULL) :val(val), next(nextNode){

    }
};
ListNode* findkthtolast(ListNode *head, int k) {
    ListNode* runner = head;
    ListNode* chaser = head;
    if (head == NULL || k < 0) {
        return NULL;
    }
    for (int i = 0; i < k; i++) {
        runner = runner->next;
    }
    while (runner != NULL) {
        chaser = chaser->next;
        runner = runner->next;
    }
    return chaser;
}
void findkthtolasttest() {
    ListNode* head = new ListNode(1, NULL);
    ListNode* node = head;
    node->next = new ListNode(2, NULL);
    node = node->next;
    node->next = new ListNode(8, NULL);
    node = node->next;
    node->next = new ListNode(4, NULL);
    node = node->next;
    node->next = new ListNode(7, NULL);
    node = node->next;
    node->next = new ListNode(0, NULL);
    node = node->next;
    node->next = new ListNode(4, NULL);
    node = node->next;
    node->next = NULL;
    cout << findkthtolast(head,3)->val << endl;
}
int main() {
    findkthtolasttest();
    return 0;
}

Tips

None

版权声明:本文为博主原创文章,未经博主允许不得转载。

To find the kth to Last Element of a Singly Linked List

标签:

原文地址:http://blog.csdn.net/lionpku/article/details/47048251

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!