題目:
給你一個鏈表,每 k 個節點一組進行翻轉,請你返回翻轉後的鏈表。
k 是一個正整數,它的值小於或等於鏈表的長度。
如果節點總數不是 k 的整數倍,那麼請將最後剩餘的節點保持原有順序。
示例:
給你這個鏈表:1->2->3->4->5
當 k = 2 時,應當返回: 2->1->4->3->5
當 k = 3 時,應當返回: 3->2->1->4->5
說明:
你的算法只能使用常數的額外空間。
你不能只是單純的改變節點內部的值,而是需要實際進行節點交換。
代碼:
package net.mujiwulian.luckdraw.test;
import java.util.List;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public static ListNode reverseKGroup(ListNode head, int k) {
ListNode hair=new ListNode(0);
hair.next=head;
ListNode pre=hair;
ListNode end=hair;
while (end.next!=null){
//查找到end
for(int i=0;i<k&&end!=null;i++){
end=end.next;
}
if(end==null){
break;
}
//找到start
ListNode start=pre.next;
//找到切斷後的鏈表頭
ListNode next =end.next;
//切斷鏈表進行逆序轉換
end.next=null;
//hair尾指針指向逆序完成的鏈表頭
pre.next=reverse(start);
//逆序完成的鏈表尾接上next
start.next=next;
//設置pre和end爲逆序鏈表尾部節點
pre=start;
end=pre;
}
return hair.next;
}
//鏈表翻轉函數
public static ListNode reverse(ListNode head){
ListNode listNode=head.next;
head.next=null;
while (listNode!=null){
//存儲下一個節點
ListNode nextNode=listNode.next;
//該節點尾部指向頭節點
listNode.next=head;
//頭節點==當前節點
head=listNode;
//當前節點指向下一個節點
listNode=nextNode;
}
return head;
}
public static void main(String[] args) {
ListNode listNode3=new ListNode(3);
ListNode listNode1=new ListNode(1);
ListNode listNode2=new ListNode(2);
ListNode listNode4=new ListNode(4);
ListNode listNode5=new ListNode(5);
ListNode listNode6=new ListNode(6);
ListNode listNode7=new ListNode(7);
ListNode listNode8=new ListNode(8);
ListNode listNode9=new ListNode(9);
listNode1.next=listNode2;
listNode2.next=listNode3;
listNode3.next=listNode4;
listNode4.next=listNode5;
listNode5.next=listNode6;
listNode6.next=listNode7;
listNode7.next=listNode8;
listNode8.next=listNode9;
ListNode temp=listNode1;
while (temp!=null){
System.out.print(temp.val);
temp=temp.next;
}
System.out.println();
ListNode header= reverseKGroup(listNode1,3);
temp=header;
while (temp!=null){
System.out.print(temp.val);
temp=temp.next;
}
}
}
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。