找到⼀个未知长度单链表的倒数第K个节点
单链表,c语言2016-07-21
转载请注明地址:http://blog.csdn.net/liulongling/article/details/50983318
题目:
找到⼀个未知长度单链表的倒数第K个节点
提示:
head—>1—>2—>3—>4—>5—>6—>7—>8—>9—>10—>NULL.其中倒数第0个节点是NULL,倒数第1个节点是10,倒数第10个节点是1.
如上图可以看出,遍历pPcur的同时将pos--,直到pos等于0时将pPre++,最后发现pCur最后指向空时,pPre指向的位置就是反向pos的位置。
// // 找到⼀个未知长度单链表的倒数第K个节点.c // c++ // // Created by 刘龙玲 // Copyright © 2016年 liulongling. All rights reserved. // #include <stdio.h> typedef struct Node { int num; struct Node* next; }Node; Node* listNodeCreat() { Node* head = NULL; head = (Node*)malloc(sizeof(Node*)); if(head == NULL) { return NULL; } head->num = -1; head->next = NULL; Node* pCur = head; Node* pNew = NULL; for(int i = 1;i < 11;i++) { pNew = (Node*)malloc(sizeof(Node*)); if(pNew == NULL) { break; } pNew->num = i; pNew->next=NULL; pCur->next = pNew; pNew->next=NULL; pCur = pNew; } return head; } Node* findNodeByK(Node* head,int pos) { Node *pPre = NULL; Node *pCur = NULL; if(head == NULL || pos<=0) { return NULL; } pPre = head; pCur = head; while(pos > 0) { pCur = pCur ->next; pos--; if(pCur == NULL) { return NULL; } } while(pCur!=NULL)//上图红色区域表示该代码执行的地方 { pCur = pCur->next; pPre = pPre->next; } return pPre; } int main() { Node* head =listNodeCreat(); for(int i = 0;i < 11;i++) { Node* node = findNodeByK(head, i); if(node!=NULL) { printf("i= %d num= %d\n",i,node->num); }else{ printf("没有找到%d node\n",i); } } return 0; }