遍历一遍找出链表倒数第K个节点

来源:互联网 发布:淘宝助理5.0旧版本 编辑:程序博客网 时间:2024/06/06 15:47
#include <stdio.h>#include <stdlib.h>#include <string.h>//类似的问题还有求链表的中间节点判断一个单向链表是否形成了环形结构 struct Node{int node_val;Node* node_next;};Node* findNode(Node* pHead,unsigned int k){if(pHead==NULL||k=0) return NULL;Node *Head = pHead;Node *Behind = pHead;for(int i=0;i<k-1;++i){if(Head->node_next!=NULL){Head = Head->node_next;}else{return NULL;}}//此时head在k-1的位置,然后两个指针都同时往后走while(Head->node_next!=NULL){Behind=Behind->node_next;Head=Head->node_next;}return Behind; }

0 0
原创粉丝点击