题目
将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。
数据范围:
0≤n≤2000 , 1≤k≤2000 ,链表中每个元素都满足 0≤val≤1000
要求空间复杂度 O(1),时间复杂度
例如:
给定的链表是 1→2→3→4→5对于 k=2 , 你应该返回 2→1→4→3→5对于 k=3 , 你应该返回 3→2→1→4→5
思路
先得到链表的长度,根据k进行分组,在每个组内进行链表反转,用一个哨岗节点来指向反转后的组链表,同时一直将哨岗节点更新到最后一位。
代码
python版本
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @param k int整型
# @return ListNode类
#
class Solution:
def reverseKGroup(self , head: ListNode, k: int) -> ListNode:
# write code here
if(k==1 or head==None):
return head
length = self.length(head)
group = length//k
res = ListNode(-1)
now = res
for i in range(group):
tmp = None
for j in range(k):
nn = head.next
head.next = tmp
tmp = head
head = nn
now.next = tmp
while(now.next):
now = now.next
now.next = head
return res.next
def length(self, head:ListNode):
count = 1
while(head.next):
count +=1
head = head.next
return count
C++版本
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
if(k==1 || head==nullptr){
return head;
}
int length = Solution::length(head);
int group = length/k;
ListNode node = ListNode(-1);
ListNode *res = &node; //new ListNode(0);
ListNode *now = res;
for(int i = 0; i<group; i++){
ListNode *tmp=nullptr;
for(int j =0; j<k; j++){
ListNode* nn = head->next;
head->next = tmp;
tmp = head;
head = nn;
}
now->next = tmp;
while(now->next){
now = now->next;
}
}
now->next = head;
return res->next;
}
int length(ListNode* head){
int node_num = 1;
while(head->next){
node_num++;
head = head->next;
}
return node_num;
}
};