思路分析
(1)遍歷單鏈表,獲取當前鏈表的當前結點curNode,並記錄當前結點的下一個結點nextNode;
(2) 新建一個反轉鏈表reverseHead,將當前結點curNode插入到reverseHead的最前面的結點(curNode.next=reverseHead.next;reverseHead.next=curNode)
(3) 只要當前鏈表沒有遍歷完成(curNode!=null),獲取下一個結點爲當前結點,重複執行Step一、Step2
代碼java
public void reverse(){ //鏈表爲空或者只有一個結點,則不須要反轉 if(head.next==null || head.next.next==null){ return ; } Node reverseHead=new Node(0);//反轉結點的head指針; Node cur=head.next;//指向原鏈表的當前結點 Node next=null; while(cur!=null){ next= cur.next;// 記錄當前結點的下一個結點 cur.next=reverseHead.next; reverseHead.next=cur; cur=next; } head=reverseHead; }
思路分析: 遍歷鏈表,計數器加一便可算法
public int getLength(){ int count=0; Node tmp=head.next; while(tmp!=null){ count++; tmp=tmp.next; } return count; }
思路分析: 首先獲取該鏈表總的個數Count,則倒數第k個結點即爲順數第Count-k個結點指針
public Node getLastIndexNode(int k){ int count=getLength(); if(k>count){ return null; } Node tmp=head.next; int index=1; while(index <= count-k){ index++; tmp=tmp.next; } return tmp; }
思路分析:
(1)設置兩個指針tmp1和tmp2分別指向鏈表1和鏈表2
(2)依次比較兩個大小,把小的增長到新鏈表的尾部直到循環退出;
(3)把其中一條沒有完成的鏈表繼續鏈接到tmp的尾部;code
public Node mergeSingleLinkedList(Node head1,Node head2){ Node tmp1=head1.next; Node tmp2=head2.next; if(head1.next==null){ return head2; } if(head2.next==null){ return head1; } Node newHead=new Node(0); Node tmp =newHead; while(tmp1!=null && tmp2!=null){ if(tmp1.data>tmp2.data){ tmp.next=tmp2; tmp=tmp2; tmp2=tmp2.next; }else{ tmp.next=tmp1; tmp=tmp1; tmp1=tmp1.next; } } //上面的while循環跳出,必然是有一個先跳出循環 if(tmp1==null){ tmp.next=tmp2; }else{ tmp.next=tmp1; } head=newHead; return tmp; }
雙向鏈表相對於單向鏈表的優勢
(1)單向鏈表遍歷時,只能前後遍歷,而雙向鏈表能夠向前遍歷
(2)雙向鏈表能夠實現自我結點的刪除,而單向鏈表刪除某個結點的時候,是刪除當前結點的下一個結點get
由n個結點圍城一個環,編號爲[1,n],從第k個結點(1<=k<=n)開始,從1開始計數,數到m的結點提取出來,而後再從該節點的下一個結點開始,又從1到m開始數,而後取出來,直到全部的節點都取出來爲止,求被取出來的結點的順序。
解決思路
josehu環問題:假設鏈環中有5個節點,從1節點開始數,數2次
算法實現步驟:
(1)建立joshu環(含有一個指向第一個節點的指針first)
(2)新建一個curNode指針,讓其指向first的前一個結點(curNode.nextfirst)
(3)找到起始點,同時移動first和curNode指針,移動startNo-1次,此操做始終保持curNode.nextfirst
(4)開始數數,同時移動指針curNode和first的次數爲:countNum-1次。
(5)判斷curNode==first,若是成立,則進行(6),不然進行(7)
(6)此時環中只剩下最後一個結點,打印該結點信息便可
(7)刪除first結點,即first=first.next;curNode.next=fist;繼續執行(3)、(4)ast