2.2

Implement an algorithm to find the nth to last element of a singly linked list.

分析:查找鏈表倒數第n個元素,這在劍指offer上有相同的習題

Node* get_lastn(Node* head,int n){
	if(head==NULL||n<=0) return NULL;
	Node* front=head;
	Node* behind=head;
	while(n>1){
		behind=behind->next;
		if(behind==NULL) return NULL;
		n--;
	}
	while(behind->next!=NULL){
		front=front->next;
		behind=behind->next;
	}
	return front;
}

發佈了286 篇原創文章 · 獲贊 8 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章