一、算法思想:
只遍历一次链表。设置2个指针,当第一个指针从表头向前走到第n-1个节点时,第二个指针开始从表头出发。当第一个指针走到尾节点时,第二个指针的位置即为倒数第n个节点
一、代码:
#include "stdafx.h" #include<windows.h> #include<iostream> #define LIST_LEN 10 using namespace std; struct list_node { int value; list_node *next; }; list_node *init_list(int len) { list_node *head, *p, *q; p = (list_node *)malloc(sizeof(list_node)); p->value = 0; head = p; for (int i = 1; i < len; i++) { q = (list_node *)malloc(sizeof(list_node)); q->value = 2 * i; p->next = q; p = q; } p->next = NULL; return head; } int show_list(list_node *head) { if (head == NULL) return 0; list_node *p = head; while (p) { printf("%4d", p->value); p = p->next; } printf(" "); return 0; } list_node *NthToLastNode(list_node *head, int n) { if (head == NULL || n <= 0) return 0; list_node *first, *second; first = head; //第一次循环先让第一个快指针走len个节点 for (int i = 0; i < n - 1; i++) { first = first->next; } second = head; //此时,快指针和慢指针差距为n个节点 //循环里,第一个节点和第二个节点同时往后移,当first->nest等于null时 ,second刚好是倒数第n个节点 while (first->next != NULL) { first = first->next; second = second->next; } return second; } int main() { list_node *head = init_list(LIST_LEN); show_list(head); list_node *temp = NthToLastNode(head, 3); printf("%4d ", temp->value); system("pause"); return 0; }