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

#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; 
}

发布了93 篇原创文章 · 获赞 6 · 访问量 21万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章