每天一个小算法(5)----找到链表倒数第K个结点
估计这个问题在面试中被问烂了。
思路是先找到正数的第K个结点的指针pT,然后和指向头结点的指针pN一起向后移动,直到第K个指针指向NULL,此时pN指向的结点即倒数第K个结点。
如图:
1 #include <stdio.h> 2 #include <time.h> 3 #include <stdlib.h> 4 typedef struct Node 5 { 6 int data; 7 Node* next; 8 }Node, *List; 9 10 11 List createList(int num) //随机生成数字,构造链表 12 { 13 List aList = (List)malloc(sizeof(Node)); 14 aList->next = NULL; 15 aList->data = 0; 16 Node* qT = aList; 17 18 for ( int i=0; i< num; ++i) 19 { 20 Node* pTN = (Node*)malloc(sizeof(Node)); 21 pTN->data = rand()%100; 22 pTN->next = NULL; 23 qT->next = pTN; 24 qT = pTN; 25 } 26 return aList; 27 } 28 29 void printList(List aList) //正序打印链表 30 { 31 if ( aList == NULL || aList->next == NULL ) 32 return; 33 34 Node* pT = aList->next; 35 printf("element of the list:\n\t"); 36 while( pT != NULL ) 37 { 38 printf("%d ", pT->data); 39 pT = pT->next; 40 } 41 42 printf("\n"); 43 } 44 45 //链表倒数第K个节点主算法 46 Node* rfind_K_node(List aList, int K) 47 { 48 if ( aList == NULL || K <=0 ) 49 return NULL; 50 51 Node* pT = aList; 52 Node* pN = aList; 53 for ( int i=0; i< K; ++i ) 54 { 55 pT = pT->next; 56 } 57 58 while ( pT != NULL ) 59 { 60 pN = pN->next; 61 pT = pT->next; 62 } 63 64 return pN; 65 } 66 67 void deleteList(List aList) //删除链表 68 {} 69 70 int main(int argc, char const *argv[]) 71 { 72 srand((int)time(0)); 73 List aList = createList(7); 74 printList(aList); 75 printf("The bottom %d Node data is %d\n", 5, rfind_K_node(aList, 5)->data); 76 deleteList(aList); 77 78 return 0; 79 }