标签:
#include <stdio.h> #include <stdlib.h> typedef struct LinkNode { struct LinkNode* next; int data; }LinkList; /*创建链表*/ void createLinkList(LinkList* head, int* a, int n) { int i = 0; LinkNode* node = NULL; while (i < n) { node = new LinkNode; node->next = head->next; node->data = a[i]; head->next = node; i++; } } /*找到倒数第K个数*/ LinkNode* findKNum(LinkList* head, int k) { LinkNode* p = head->next; LinkNode* q; int i = 0; /*先让p走k步*/ while (p!=NULL && i<k) { p = p->next; i++; } if (i < k) { return NULL; } q = head->next;; while (p != NULL) { p = p->next; q = q->next; } return q; } /*打印链表*/ void printLinkList(LinkList* head) { LinkNode* node = head->next; while (node != NULL) { printf("%d\t", node->data); node = node->next; } printf("\n"); } int main() { LinkList head = {0}; LinkList* node = NULL; int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1}; createLinkList(&head, a, 9); printLinkList(&head); node = findKNum(&head, 10); if (node == NULL) { printf("NULL\n"); return 0; } printf("k num %d\n", node->data); return 0; }
标签:
原文地址:http://blog.csdn.net/yuanwei1314/article/details/43082953