输入一个单向链表,输出该链表中倒数第k 个结点。链表的倒数第0个结点为链表的尾指针。

来源:互联网 发布:笔记本外置光驱 知乎 编辑:程序博客网 时间:2024/05/17 07:42
两个指针,第一个先走K步,第二个再和第一个一起走,一直到第一个走到尾结点。那第二个指针的位置就是所求。
#include <stdio.h>#include <stdlib.h>typedef struct node{int data;struct node* next;} Node;Node* create_NodeList(int a[],int lenght);Node* find_last(Node *hnode,int k);void free_NodeList(Node* pNode);void pr_nodeList(const Node *pNode);int main(void) {int a[]={1,23,435,45,65,65,76,78,89,3};int i=3;Node *pNode=create_NodeList(a,sizeof(a)/sizeof(int));pr_nodeList(pNode);printf("find last %d --> %d \n",i,find_last(pNode,i)->data);free_NodeList(pNode);return EXIT_SUCCESS;}Node* find_last(Node *hnode,int k){Node *p1=hnode,*p2=hnode;if(k<0 || hnode == NULL)return NULL;for(;k>0;k--){if(p1->next) p1=p1->next;else return NULL;}while(p1->next){p1=p1->next;p2=p2->next;}return p2;}Node* create_NodeList(int a[],int lenght){int i=0;Node* pN=NULL,*pTmp=NULL;for(i=0;i<lenght;i++){pTmp=(Node*)malloc(sizeof(Node));pTmp->data=a[i];pTmp->next=NULL;pTmp->next=pN;pN=pTmp;}return pN;}void free_NodeList(Node* pNode){Node *pTmp;while(pNode){pTmp=pNode;pNode=pNode->next;free(pTmp);}}void pr_nodeList(const Node *pNode){int i=0;while(pNode){printf("%-2d: %d\n",i++,pNode->data);pNode=pNode->next;}}

原创粉丝点击