九度 链表中倒数第k个结点

/*

 * a.cpp

 *

 *  Created on: 2013-10-7

 *      Author: wangzhu

 */



#include<cstdio>

#include<iostream>

using namespace std;

struct Node {

    int key;

    Node* next;

};



void addToHead(Node* root, int val) {

    Node* tempNode = root->next;



    Node* node = new Node;

    node->key = val;

    node->next = tempNode;



    root->next = node;

}



void addToTail(Node* root, int val) {

    Node* node = new Node;

    node->key = val;

    node->next = NULL;

    if (root->next == NULL) {

        root->next = node;

    } else {

        Node* tempNode = root->next;

        while (tempNode->next != NULL) {

            tempNode = tempNode->next;

        }

        tempNode->next = node;

    }

}



void printHead(Node* node, int k) {

    for (int i = 1; i < k; i++) {

        node = node->next;

    }

    printf("%d\n", node->key);

}



void printTail(Node* node, int k) {

    Node* firstNode = node;

    Node* secondNode = node;

    for (int i = 1; i < k; i++) {

        firstNode = firstNode->next;

    }

    while (firstNode->next != NULL) {

        firstNode = firstNode->next;

        secondNode = secondNode->next;

    }

    printf("%d\n", secondNode->key);

}

int main() {

    freopen("data.in", "r", stdin);

    Node* root;

    int n, k, val;

    while (~scanf("%d%d", &n, &k)) {

        root = new Node;

        root->next = NULL;

        for (int i = 0; i < n; i++) {

            scanf("%d", &val);

            //addToHead(root, val);

            addToTail(root,val);

        }

        if (n == 0 || k == 0 || n < k) {

            printf("NULL\n");

        } else {

            //printHead(root->next, k);

            printTail(root->next,k);

        }

    }

    return 0;

}

 

你可能感兴趣的:(链表)