網(wǎng)絡廣告設計案例網(wǎng)站關(guān)鍵詞排名優(yōu)化方法
給你鏈表的頭節(jié)點?
head
?,每?k
?個節(jié)點一組進行翻轉(zhuǎn),請你返回修改后的鏈表。
k
?是一個正整數(shù),它的值小于或等于鏈表的長度。如果節(jié)點總數(shù)不是?k
?的整數(shù)倍,那么請將最后剩余的節(jié)點保持原有順序。你不能只是單純的改變節(jié)點內(nèi)部的值,而是需要實際進行節(jié)點交換。
? ? ? ?對鏈表進行k個節(jié)點的反轉(zhuǎn),首先我們要先知道鏈表的節(jié)點個數(shù)有多少個?才能知道我們需要翻轉(zhuǎn)多少次?最后不夠的節(jié)點是不需要翻轉(zhuǎn)的
int n=0;ListNode cur=head;//計算出列表的長度while(cur!=null){n++;cur=cur.next;}
為了使head節(jié)點不具有特殊性,我們經(jīng)常會在head節(jié)點前加一個虛擬頭結(jié)點dummyHead
?過程如下:
?序號12345的代碼:
for (int i =0; i <k; i++) {ListNode next=curNode.next;curNode.next=pre;pre=curNode;curNode=next;}
序號67的代碼:
ListNode next=p0.next;p0.next.next=curNode;p0.next=pre;p0=next;
? ? ? ?通過while的循環(huán),就可以將k個節(jié)點進行反轉(zhuǎn),多指針這種方法也是比較好想的,但是就是比較容易繞,希望大家可以看著我畫的圖進行理解
源代碼:
public ListNode reverseKGroup(ListNode head, int k) {if(head==null){return null;}int n=0;ListNode cur=head;//計算出列表的長度while(cur!=null){n++;cur=cur.next;}ListNode dummyNode=new ListNode(-1);dummyNode.next=head;ListNode pre=null;ListNode p0=dummyNode;ListNode curNode=p0.next;while(n>=k){n-=k;for (int i =0; i <k; i++) {ListNode next=curNode.next;curNode.next=pre;pre=curNode;curNode=next;}ListNode next=p0.next;p0.next.next=curNode;p0.next=pre;p0=next;}return dummyNode.next;}
下面給大家遞歸的代碼,供大家借鑒:
//遞歸反轉(zhuǎn)public ListNode reverseKGroup(ListNode head, int k) {if(head==null||head.next==null){return head;}ListNode r=head;for (int i = 0; i <k; i++) {if(r==null){return head;}r=r.next;}ListNode node=reverse(head,r);head.next=reverseKGroup(r,k);return node;}//給定區(qū)間鏈表進行反轉(zhuǎn)public ListNode reverse(ListNode head,ListNode right){ListNode pre=null,curNode=head,next=null;while(curNode!=right){next=curNode.next;curNode.next=pre;pre=curNode;curNode=next;}return pre;}