遍歷一遍找出鏈表倒數第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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章