找出鏈表倒數(shù)第n個節(jié)點元素的二個方法
更新時間:2013年11月14日 10:11:03 作者:
本文提供了找出鏈表倒數(shù)第n個節(jié)點元素的二個方法,其中一個方法是JAVA代碼實現(xiàn)
方法一:利用兩個指針p,q,首先將q往鏈表尾部移動n位,然后再將p、q一起往后移,那么當q達到鏈表尾部時,p即指向鏈表的倒數(shù)第n個節(jié)點。
node* find_nth_to_last(node* head,int n) { if(head==NULL || n<1) return NULL; node*p,*q; p=q=head; while(q!=NULL && n--){ q=q->next; } if(n>=0) return NULL; while(p!=NULL && q!=NULL){ p=p->next; q=q->next; } return p; }
方法二:可以先計算出節(jié)點個數(shù),即從頭到尾遍歷一次鏈表,得到個數(shù)m,那么倒數(shù)第n個元素也即第m-n+1個元素.與方法一是同樣的思維,只是具體操作方式不同,代碼略.
JAVA代碼:
LinkedListNode nthToLast(LinkedListNode head, int n) { if (head == null || n < 1) { return null; } LinkedListNode p1 = head; LinkedListNode p2 = head; for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead if (p2 == null) { return null; // not found since list size < n } p2 = p2.next; } while (p2.next != null) { p1 = p1.next; p2 = p2.next; } return p1; }
復制代碼 代碼如下:
node* find_nth_to_last(node* head,int n) { if(head==NULL || n<1) return NULL; node*p,*q; p=q=head; while(q!=NULL && n--){ q=q->next; } if(n>=0) return NULL; while(p!=NULL && q!=NULL){ p=p->next; q=q->next; } return p; }
方法二:可以先計算出節(jié)點個數(shù),即從頭到尾遍歷一次鏈表,得到個數(shù)m,那么倒數(shù)第n個元素也即第m-n+1個元素.與方法一是同樣的思維,只是具體操作方式不同,代碼略.
JAVA代碼:
復制代碼 代碼如下:
LinkedListNode nthToLast(LinkedListNode head, int n) { if (head == null || n < 1) { return null; } LinkedListNode p1 = head; LinkedListNode p2 = head; for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead if (p2 == null) { return null; // not found since list size < n } p2 = p2.next; } while (p2.next != null) { p1 = p1.next; p2 = p2.next; } return p1; }
相關(guān)文章
Activiti工作流學習筆記之自動生成28張數(shù)據(jù)庫表的底層原理解析
這篇文章主要介紹了Activiti工作流學習筆記之自動生成28張數(shù)據(jù)庫表的底層原理解析,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03request如何獲取body的json數(shù)據(jù)
這篇文章主要介紹了request如何獲取body的json數(shù)據(jù)操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06spring boot使用sonarqube來檢查技術(shù)債務
今天小編就為大家分享一篇關(guān)于spring boot使用sonarqube來檢查技術(shù)債務,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12